-2

I want to split the numbers out of a string and put them in an array using Regex.

For example, I have a string 23a43b3843c9293k234nm5g%>and using regex I need to get [23,43,3843,9293,234,5] in an array

how can i achieve this?

TastyCode
  • 5,679
  • 4
  • 37
  • 42
PhoonOne
  • 2,678
  • 12
  • 48
  • 76
  • Another one [Regex using javascript to return just numbers](http://stackoverflow.com/questions/1183903/regex-using-javascript-to-return-just-numbers) – Tushar Mar 02 '16 at 04:00

2 Answers2

3

Use String.prototype.match()

The match() method retrieves the matches when matching a string against a regular expression

Edit: As suggested by Tushar, Use Array.prototype.map and argument as Number to cast it as Number.

Try this:

var exp = /[0-9]+/g;
var input = "23a43b3843c9293k234nm5g%>";
var op = input.match(exp).map(Number);
console.log(op);
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Rayon
  • 36,219
  • 4
  • 49
  • 76
1
var text = "23a43b3843c9293k234nm5g%>";
var regex = /(\d+)/g;
alert(text.match(regex));

You get a match object with all of your numbers.

The script above correctly alerts 23,43,3843,9293,234,5.

see Fiddle http://jsfiddle.net/5WJ9v/307/

S M
  • 3,133
  • 5
  • 30
  • 59