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?
importance of /g in Javascript regex
Moderator: General Moderators
- raghavan20
- DevNet Resident
- Posts: 1451
- Joined: Sat Jun 11, 2005 6:57 am
- Location: London, UK
- Contact:
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
I can 
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".
The first one just finds the first occurence of the match, the second one keeps going until all matches are found 
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>- raghavan20
- DevNet Resident
- Posts: 1451
- Joined: Sat Jun 11, 2005 6:57 am
- Location: London, UK
- Contact: