在JavaScript中从字符串中删除所有非数字字符

时间:2021-05-25 09:33:40

Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.

考虑一个非dom场景,您希望使用JavaScript/ECMAScript从字符串中删除所有非数字字符。应该保留范围为0 - 9的任何字符。

var myString = 'abc123.8<blah>';

//desired output is 1238

How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.

如何用普通的JavaScript实现这一点?请记住,这是一个非dom场景,所以jQuery和其他涉及浏览器和按键事件的解决方案不适合。

6 个解决方案

#1


963  

Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:

使用字符串的.replace方法使用\D的regex,这是一个与所有非数字匹配的快捷字符类:

myString = myString.replace(/\D/g,'');

#2


262  

If you need this to leave the dot for float numbers, use this

如果你需要这个来让浮点数留下点,用这个。

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"

#3


31  

Use a regular expression, if your script implementation supports them. Something like:

如果脚本实现支持正则表达式,请使用正则表达式。喜欢的东西:

myString.replace(/[^0-9]/g, '');

#4


19  

You can use a RegExp to replace all the non-digit characters:

您可以使用RegExp替换所有非数字字符:

var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238

#5


14  

Something along the lines of:

类似于:

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

#6


-3  

we are in 2017 now you can also use ES2016

2017年我们也可以使用ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

结果是

1238

#1


963  

Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:

使用字符串的.replace方法使用\D的regex,这是一个与所有非数字匹配的快捷字符类:

myString = myString.replace(/\D/g,'');

#2


262  

If you need this to leave the dot for float numbers, use this

如果你需要这个来让浮点数留下点,用这个。

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"

#3


31  

Use a regular expression, if your script implementation supports them. Something like:

如果脚本实现支持正则表达式,请使用正则表达式。喜欢的东西:

myString.replace(/[^0-9]/g, '');

#4


19  

You can use a RegExp to replace all the non-digit characters:

您可以使用RegExp替换所有非数字字符:

var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238

#5


14  

Something along the lines of:

类似于:

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

#6


-3  

we are in 2017 now you can also use ES2016

2017年我们也可以使用ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

结果是

1238