var str="boy pig donkey";
var patt=/(^| )(\\S+)( |$)/g;
var result;
while(result=patt.exec(str)){
document.write("Returned value: " + result[2] + "<br>");
}
output:
Returned value: boy
Returned value: donkey
Why doesn’t it output:
Returned value: boy Returned value: pig
Returned value: donkey
I would have thought that on the second iteration, the space before “pig” would match the first parenthesized part of the RegExp, “pig” should match the second parenthesized part of the RegExp and the space after “pig” should match the third.
Kind of answered my own question here.
The reason it ignores pig is because the first iteration matches "boy " (including the space).
The second iteration will then ignore "boy " and start with “pig donkey”.
The first character in this new string that matches the reg exp. is the space before donkey.
Therefore writing: var str=“boy pig donkey”; (with double spaces) produces the required result of:
Returned value: boy
Returned value: pig
Returned value: donkey
Now a new question. How would I write a reg exp with the /g switch to get the above result from a list of names separated only by one space (such as a list of class names)?
var str="boy pig donkey";
var patt=/\\b\\w+\\b/g; // \\b is a word boundary \\w+ any word character one or more times
var result;
while(result=patt.exec(str)){
document.write("Returned value: " + result[0] + "<br>");
}