2013-03-17 52 views
4
var price = "$23.03"; 
var newPrice = price.replace('$', '') 

这个工作,但价格还可以,如:的jQuery删除所有的字符,但数字和小数

var price = "23.03 euros"; 

和许多许多其他货币。

是否有,我可以只留下数字和小数(。)?

+2

这是如何关系到jQuery的?这是纯粹的JavaScript,绝不使用jQuery库。 – 2013-03-17 18:13:01

+1

你有什么尝试?例如,您是否尝试过查找'replace'的文档? – 2013-03-17 18:14:18

回答

22
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. 
} 
1
var newprice = price.replace(/\D+$/, ''); 
相关问题