[英]how to separate an integer number from a string in JS?
Sometimes in a HTML file, we have a <p>
tag that shows the price of a product.有时在 HTML 文件中,我们有一个显示产品价格的<p>
标签。 For example the price is "1,200,000 Dollar"
.例如价格是"1,200,000 Dollar"
。 Now a user added this product to the cart.现在用户将此产品添加到购物车。 I want that the webpage display the total price in the cart.我希望网页显示购物车中的总价格。
Now in JavaScript I want the program separate the number of price from string and put that in a variable.现在在 JavaScript 中,我希望程序将价格数字与字符串分开并将其放入变量中。 Here in the example that I said the <p>
tag shows "1,200,000 Dollar"
.在我所说的示例中, <p>
标签显示"1,200,000 Dollar"
。 Now I want to put just the number(in the example the number is 1,200,000
) in a variable to calculate the total price later.现在我只想将数字(在示例中为1,200,000
)放入一个变量中,以便稍后计算总价。 What should I do?我应该怎么办?
You can also use a split function in this case.在这种情况下,您也可以使用拆分 function。
const currencyString="1,000,000 Dollars";
const currencyNumber=Number(currencyString.split(' ')[0].replace(/,/g, ''));
Does the below answer your question...以下是否回答了您的问题...
var input = '1,200,000 Dollar';
var output = Number(input.replace(/[^0-9\-\.]/g, ''));
First we remove all non-digit characters with .replace
method and then create a new Number
value.首先,我们使用.replace
方法删除所有非数字字符,然后创建一个新的Number
值。
A few other usage examples:其他一些使用示例:
function stringToNumber(string) { return Number(string.replace(/[^0-9\-\.]/g, '')); } var inputs = [ '1,000,000 Dollars', '$1,000,000.50', '-50.12 USD' ]; for (var i = 0; i < inputs.length; i++) { console.log(inputs[i], stringToNumber(inputs[i])); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.