Thanks, rpg_digital, would this be the whole code?
const field = document.querySelector('#collocazione');
const trunc = (num, places = 0) => {
// if places is 0 or not supplied
// return an integer as a String
if (places <= 0) {
return String(Math.trunc(num.split(' ')[0]))
}
// using the RexExp constructor to dynamically create a regex
// so places = 2 -> regex = \d+\.\d{1,2}
const regex = new RegExp(`\\d+\\.\\d{1,${places}}`)
const match = num.match(regex)
return (match !== null) ? match[0] : null
}
// truncate group methods
const truncGroups = [
{
groupRx: /8[4-6][0-9].*/,
truncate: (code) => {
// we can split a string using a regex
// / ([A-Z]{2})/ splits code on a possible space followed by
// 2 letters and capture those letters e.g.
// 861.44 CU -> ['861.44', 'CU']
// 861.44 7 -> ['861.44 7']
const [num, letters] = code.split(/ ([A-Z]{2})/)
// truncate number to 1 decimal place
const truncNumber = trunc(num, 1)
// if letters exist?
return (letters)
? `${truncNumber} ${letters}` // true: return with letters
: `${truncNumber}` // false: return without
}
},
{
groupRx: /80[1-7]/,
truncate: (code) => trunc(code), // return integer
},
{
groupRx: /839.3[16]*/,
truncate: (code) => trunc(code, 2) // return to 2 decimal places
}
]
const formatCode = (code) => {
// loop through truncGroups
for (const { groupRx, truncate } of truncGroups) {
// test the regex against the code
if (groupRx.test(code)) {
return truncate(code)
}
}
// didn't match so return original
return code
}
const testCodes = [
'847.467 4', // 847.4
'850.767 456', // 850.7
'869.999 3', // 869.9
'861.39 CU', // 861.3 CU
'863.456 CL', // 863.4 CL
'861.444 05 AR', // 861.4 AR
'869.347 5 BR', // 869.3 BR
// Another group starting with 80[1-7]*
'802.556 667567', // 802
'805.875 4', // 805
// Another group starting with 839.3[1,6]*
'839.315 6', // 839.31
'839.366 87', // 839.36
'111.aaa'// 111.aaa
]
// check console!
testCodes.forEach((code) => console.log(code, formatCode(code)))