javascript jQuery 删除除数字和小数以外的所有字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15464306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:51:03  来源:igfitidea点击:

jQuery remove all characters but numbers and decimals

javascriptreplacecurrency

提问by user2179950

var price = ".03";
var newPrice = price.replace('$', '')

This works, but price can also be such as:

这有效,但价格也可以是:

var price = "23.03 euros";

and many many other currencies.

以及许多其他货币。

Is there anyway that I could leave only numbers and decimal(.)?

无论如何我只能留下数字和小数(。)?

回答by Matt Cain

var newPrice = price.replace(/[^0-9\.]/g, '');

No jQuery needed. You will also need to check if there is only one decimal point though, like this:

不需要jQuery。您还需要检查是否只有一个小数点,如下所示:

var decimalPoints = newPrice.match(/\./g);

// Annoyingly you have to check for null before trying to
// count the number of matches.
if (decimalPoints && decimalPoints.length > 1) {
    // do whatever you do when input is invalid.
}

回答by Tirupathi Raju

var newprice = price.replace( /\D+$/, '');