简体   繁体   English

如何仅将字符串数字转换为数字?

[英]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.

相关问题 如何转换数字的后3位? - How to convert the last 3 digits of the number? 如果字符串是精确数字,如何将字符串转换为浮点数,不仅以 javascript 中的数字开头 - How to convert string to float if it is an exact number, not only start with number in javascript 如何在JavaScript中从数字数组或数字字符串创建整数或数字 - How to create an integer or number from array of digits or string of digits in JavaScript 如何将字符串转换为数组,数字作为其元素? - How to convert a String to an Array , digits as its elements? 仅输出后一个字符串,其数字总和等于javascript中的最大数字 - Outputting only the latter string with digits that sum the largest number in javascript 如何在开始时转换数字,除了反应原生的最后4位数字 - How to convert number in start except last 4 digits in react native 将数字转换为数字的反向数组? - Convert number to reversed array of digits? 将数字转换为反转的数字数组 - Convert number to a reversed array of digits 将一个字符串(仅包含数字)添加到数字中会导致一个数字(根据isNaN)看起来应该是一个字符串? - Adding a string (with only digits in it) to a number results in a number (according to isNaN) which looks like it should have been a string? 如何只允许数字输入到输入[type =“number”]字段? - How to allow only digits to be entered into an input[type=“number”] field?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM