jQuery删除所有字符,但数字和小数

jQuery remove all characters but numbers and decimals

本文关键字:数字 小数 字符 删除 jQuery      更新时间:2023-09-26
var price = "$23.03";
var newPrice = price.replace('$', '')

这个可以,但是price也可以这样:

var price = "23.03 euros";

和许多其他货币。

是否可以只留下数字和小数(.)?

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

不需要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.
}
var newprice = price.replace( /'D+$/, '');