最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex: Capturing all digits in a string, and returning as a new string of digits - Stack Overflow

programmeradmin0浏览0评论

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]+.

I've tried /[0-9]/g but this returns all digits as an array.

How do you capture, or match, every instance of a digit and return as a string?

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]+.

I've tried /[0-9]/g but this returns all digits as an array.

How do you capture, or match, every instance of a digit and return as a string?

Share Improve this question edited Feb 15, 2013 at 20:01 Rohit Jain 213k45 gold badges414 silver badges533 bronze badges asked Feb 15, 2013 at 19:52 CodyBugsteinCodyBugstein 23.4k67 gold badges225 silver badges381 bronze badges 2
  • What language are you using? – Rohit Jain Commented Feb 15, 2013 at 19:53
  • JavaScript. I updated the question – CodyBugstein Commented Feb 15, 2013 at 19:57
Add a ment  | 

3 Answers 3

Reset to default 3

Just replace all the non-digits from the original string:

var s = "foo 123 bar 456";
var digits = s.replace(/\D+/g, "");

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

You can replace all the non-digits character rather than extracting the digits:

var str = "some string 22 with digits 2131";
str = str.replace(new RegExp("\D","g"),"");

\D is same as [^\d].

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论