jQuery remove all characters but numbers and decimals

谁都会走 提交于 2019-12-07 06:05:38

问题


var price = "$23.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(.)?


回答1:


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:

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.
}



回答2:


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


来源:https://stackoverflow.com/questions/15464306/jquery-remove-all-characters-but-numbers-and-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!