const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; // const octRegex = /0x[a-z0-9]+/; // const binRegex = /0x[a-z0-9]+/; const consider = { hex : true, leadingZeros: true, decimalPoint: "\.", //skipLike: /regex/ }; function toNumber(str, options = {}){ // const options = Object.assign({}, consider); // if(opt.leadingZeros === false){ // options.leadingZeros = false; // }else if(opt.hex === false){ // options.hex = false; // } options = Object.assign({}, consider, options ); if(!str || typeof str !== "string" ) return str; let trimmedStr = str.trim(); if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; else if (options.hex && hexRegex.test(trimmedStr)) { return Number.parseInt(trimmedStr, 16); // } else if (options.parseOct && octRegex.test(str)) { // return Number.parseInt(val, 8); // }else if (options.parseBin && binRegex.test(str)) { // return Number.parseInt(val, 2); }else{ //separate negative sign, leading zeros, and rest number const match = numRegex.exec(trimmedStr); if(match){ const negative = match[1]; const leadingZeros = match[2]; const num = match[3]; //complete num const eNotation = match[4] || match[6]; if(leadingZeros.length === 1 && num[0] === ".") return Number(str); else if(!options.leadingZeros && leadingZeros.length > 0) return str; else return Number(trimmedStr); }else{ //non-numeric string return str; } } } module.exports = toNumber