Page 1 of 1

importance of /g in Javascript regex

Posted: Sun Aug 07, 2005 6:50 am
by raghavan20
I was having a doubt with using global search in Javascript regex cos I am able to search a big string without using /g.


ex:
rules:
1. a normal sentence which should not hv leading or trailing spaces
2. alphabets are only allowed
3. there can be space btw words
4. there should be an alphabet after a '\s'
var str = "this is a string";
var re =/^([a-z]+\s?[a-z]+)+$/i;

Can any of you help me understand the importance of /g with your own example?

Posted: Sun Aug 07, 2005 8:48 am
by Chris Corbyn
I can :D

The "g" modifier == global search.

Use "g" if you're looking for the same pattern multiple times in the same string.

Example:

Find a word that starts with the latter "a".

Code: Select all

<script type="text/javascript">

var theString = 'Arnold had a great big apple';

var m = theString.match(/\b(a\w*)/i);

document.write("<b>Non-global</b><br />");

for (var x=0; x<m.length; x++)
{
    document.write(x + " => " + m[x] + "<br />");
}

var m = theString.match(/\b(a\w*)/ig);

document.write("<b>Global</b><br />");

for (var x=0; x<m.length; x++)
{
    document.write(x + " => " + m[x] + "<br />");
}

</script>
The first one just finds the first occurence of the match, the second one keeps going until all matches are found ;)

Posted: Sun Aug 07, 2005 8:56 am
by raghavan20
Cheers for that mate!!!

Non-global
0 => Arnold
1 => Arnold
Global
0 => Arnold
1 => a
2 => apple

Why 'Arnold' was displayed twice?
what is '\b'

Posted: Sun Aug 07, 2005 9:01 am
by feyd
entire match, then grouped remember match.