简体   繁体   中英

How to convert only string digits to number?

 var txt = '54839257+32648-34324'; var x; for (x of txt) { if (0||1||2||3||4||5||6||7||8||9) { var con = Number(x); } else { x.toString();} document.write(con); }

In the code above i want to convert the digits inside the string to number but not plus and minus signs. I want to have them together for the result. like this: 54839257+32648-34324 . But my code gives this: 54839257NaN32648NaN34324 .

If you want to tokenize the numbers and symbols, but convert the integer values, you will need to split up the values first. The parenthesis around the symbols, inside the regular expression, allow you to capture the delimiter.

Afterwards, you can check if the value is numeric.

Edit: I changed the delimiter from [-+] to [^\\d] as this makes more sense.

 const input = '54839257+32648-34324'; const tokenize = (str) => { return str.split(/([^\\d])/g).map(x => !isNaN(x) ? parseInt(x, 10) : x); } console.log(tokenize(input));
 .as-console-wrapper { top: 0; max-height: 100% !important; }

For this case, simply you can use replace with regular expression.

const toNumber = (v) => {
     if (typeof v === "number") return v;
     if (typeof v !== "string") return;
     return  Number(v.replace(/[^0-9]/g, ""));
};

console.log(toNumber("OO7+54839257+32648-34324"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM