2013-03-17 87 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+$/, ''); 
相關問題