Rahul February 2016

How to find all regex match in a string

This might be too simple to find on web but I got problem with finding the answer.

I get string as http response text that contain substrings I want to grab all one by one to further process. Its relative URL.

for example:

var string = "div classimage a hrefstring1.png img idEMIC00001 he19.56mm wi69.85mm srcstring1.png  separated by some html         div classimage a hrefstring2.png srcstring2.png div separated by some html many such relative urls";
var re = new RegExp("[a-z]{5,10}[0-9].png");
var match = re.exec(string)
WScript.Echo (match);

This gives first match. I want to get all collection one by one. I am using Jscript. I am new to javascript.

After the answer I tried this.

var string = "div classimage a hrefstring1.png img idEMIC00001 he19.56mm wi69.85mm srcstring1.png  separated by some html         div classimage a hrefstring2.png srcstring2.png div separated by some html many such relative urls";
var re = new RegExp("[a-z]{5,10}[0-9].png", "g");
var match = re.exec(string)
WScript.Echo (match);

But no luck.

Answers


Gwendal February 2016

This should fix your problem :

var re = new RegExp("[a-z]{5,10}[0-9].png", "g");

The "g" stands for global, it'll match all occurrences in your string


BenG February 2016

use 'g' for a global search and match to get all matches:-

var string = "div classimage a hrefstring1.png img idEMIC00001 he19.56mm wi69.85mm srcstring1.png  separated by some html         div classimage a hrefstring2.png srcstring2.png div separated by some html many such relative urls";

var re = new RegExp("[a-z]{5,10}[0-9].png", 'g');

var matches = string.match(re);

for(var i = 0; i < matches.length; i++){
    console.log(matches[i]);
}


gurvinder372 February 2016

just make it

var match = string.match(re)

instead of

var match = re.exec(string);

rest of the code seems to be fine.

Post Status

Asked in February 2016
Viewed 1,261 times
Voted 14
Answered 3 times

Search




Leave an answer