0

I am trying to run regex on a string something like

string = 'The value is ij35dss. The value is fsd53fdsfds.'

Where I want something like string.match(/The value is (.*?)\./g); to return just ['ijdss','fsdfdsfds'] and not ['The value is ijdss.', 'The value is fsdfdsfds.']

ParoX
  • 5,685
  • 23
  • 81
  • 152

1 Answers1

4

Use RegExp.exec instead, here's a sample:

var string = 'The value is ij35dss. The value is fsd53fdsfds.';
var re = new RegExp(/The value is (.*?)\./g)

var strs = []   
var m = re.exec(string)

while(m != null) {
  strs.push(m[1]);
  m = re.exec(string)
}

alert(strs)

and a jsFiddle:

If you think you will need this often, you can add this to a String.prototype:

String.prototype.matchGroup = function(re, group) {
  var m = re.exec(string);
  var strs = [];
  while(m != null) {
    strs.push(m[group]);
    m = re.exec(string);
  }
  return strs;
}

var string = 'The value is ij35dss. The value is fsd53fdsfds.';
alert(string.matchGroup(/The value is (.*?)\./g, 1));

jsFiddle:

Credits:

Community
  • 1
  • 1
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • See the edit - however, I don't see why you view it as "hackish". This is a normal way of using regexps - you match, then loop through all the matches and extract groups, seems pretty clean to me. – icyrock.com Feb 22 '12 at 02:35
  • @BHare, it's not hackish, just badly written. Could be made nicer, like: http://jsfiddle.net/SutFc/ – Qtax Feb 22 '12 at 05:59
  • 1
    I understand its not "hackish" because there exists no method in javascript to do regex like any other language I've used; That's the part that seems hackish. That the function matchGroup, as simple as it is, doesn't exist natively. – ParoX Feb 22 '12 at 12:26