How do I convert octal strings (“001”, “06”, “04”, etc.) to actual numbers while keeping the zeroes (001, 06, 04, etc.) in Node.js?
I have an array as a string, but I can’t parse that array because it has octals in it, so doing JSON.parse doesn’t do the trick.
I need actual numbers, not strings.
I can convert the string to an actual array of strings (the numbers are now the strings). This is what I have so far:
const theArray = '[03, 001, 02, 3, 44]';
// causes an error because of octals: JSON.parse(theArray);
// remove the brackets and white spaces
const octals = theArray.replace(/^[|]$/g, '').replace(/ /g, '').split(',');
// convert strings to numbers
const final = octals.map(x => {
if(x.length > 1 && x[0] === '0') return parseInt(x, 8);
else return parseInt(x, 10);
});
// final result
console.log('final: ', final);