1

I am learning JS regex, so I am thinking about this example string 99s999s99s99. Now I want to find all number sequences within this string. I tried the following:

var s = /(\d+)/g;
var a = '99s999s99s99';
s.exec(a);

var s = /(\d+)/;
var a = '99s999s99s99';
s.exec(a);

but both are producing the following output: [ '99', '99', index: 0, input: '99s999s99s99' ]

How to find all the groups of 9s?

Rajat Saxena
  • 3,834
  • 5
  • 45
  • 63

2 Answers2

1

Your regex is fine (although it will match other digits, not 9's only like your title suggests), but you're using RegExp.prototype.exec when you want String.prototype.match.

'99s999s99s99'.match( /(\d+)/g ) returns the array:

["99", "999", "99", "99"]

RegExp.prototype.exec must be called repeatedly using the same RegExp to find all the matches, otherwise it only finds one.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • I was using 'exec()' method as prescribed in JS: The Good Parts. – Rajat Saxena Dec 16 '16 at 08:28
  • @RajatSaxena They are both valid functions to use but they have different behaviour. You could use exec with a loop as per the last link in my answer, but I believe `match` will suit you better. – Paul Dec 16 '16 at 08:40
0

Check below code and link for demo:

Code:

var str = "99s999s99s99";
var pattern = /\d+/g;
var result = str.match(pattern);
console.log(result);

Execution:

var str = "99s999s99s99";
var pattern = /\d+/g;
var result = str.match(pattern);
console.log(result);

Demo Link: JS BIN

Sathvik Chinnu
  • 565
  • 1
  • 7
  • 23