[英]Regex: Capturing all digits in a string, and returning as a new string of digits
I am trying to capture all the digits of an input string. 我试图捕获输入字符串的所有数字。 The string can also contain other characters like letters so I can't simply do
[0-9]+
. 字符串也可以包含其他字符,如字母,所以我不能简单地做
[0-9]+
。
I've tried /[0-9]/g
but this returns all digits as an array. 我已经尝试了
/[0-9]/g
但这会将所有数字作为数组返回。
How do you capture, or match, every instance of a digit and return as a string? 如何捕获或匹配数字的每个实例并以字符串形式返回?
Just replace all the non-digits from the original string: 只需替换原始字符串中的所有非数字:
var s = "foo 123 bar 456";
var digits = s.replace(/\D+/g, "");
You can replace all the non-digits character rather than extracting the digits
: 您可以替换所有非数字字符而不是提取
digits
:
var str = "some string 22 with digits 2131";
str = str.replace(new RegExp("\D","g"),"");
\\D
is same as [^\\d]
. \\D
与[^\\d]
。
The other solutions are better, but to do it just as you asked, you simply need to join the array. 其他解决方案更好,但要按照您的要求执行,您只需要加入阵列。
var str = "this 1 string has 2 digits";
var result = str.match(/[0-9]+/g).join(''); // 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.