Ok, I think I need to repost my question that was originally:
Javascript Regex group multiple
with a full example. I have:
var text
This is what works:
var text = ""+
"<html> " +
" <head> " +
" </head> " +
" <body> " +
" <g:alert content='alert'/> " +
" <g:alert content='poop'/> " +
" </body> " +
"</html>";
var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/g;
var match = null;
while ( (match = regex.exec( text )) != null )
console.log(match)
Notice the /g which seems to be neccessary
exec
returns only ONE result at a time and sets the pointer to the end of that match. Therefore, if you want to get ALL matches use a while
loop:
while ((match = regex.exec( text )) != null)
{
console.log(match);
}
To get all matches at one shot, use text.match(regex)
, in which the regex has g
(global flag) specified. The g
flag will make match
find all matches to the regex in the string and return all the matches in an array.
[edit] and that's why my example HAD a g flag set! [/eoe]
var text = ""+
"<html> " +
" <head> " +
" </head> " +
" <body> " +
" <g:alert content='alert'/> " +
" <g:alert content='poop'/> " +
" </body> " +
"</html>";
// Note the g flag
var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/gm;
var match = text.match( regex );
console.log(match);
SIMPLE TEST:
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var text = ""+
"<html> " +
" <head> " +
" </head> " +
" <body> " +
" <g:alert content='alert'/> " +
" <g:alert content='poop'/> " +
" </body> " +
"</html>";
// Note the g flag
var regex = /<([a-zA-Z]*?):([a-zA-Z]*?)\s([\s\S]*?)>/gi;
var n = text.match( regex );
alert(n);
}
</script>
working perfectly...