[英]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
.像这样:
54839257+32648-34324
。 But my code gives this: 54839257NaN32648NaN34324
.但我的代码给出了这个:
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.编辑:我将分隔符从
[-+]
更改为[^\\d]
因为这更有意义。
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.