Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems picking out bits of text with regular expressions. 2

Status
Not open for further replies.

deadpool42

Programmer
May 24, 2004
40
0
0
I want to end up with an array containing each bit of text that's surrounded by <row> tags, but I can only get it to match the first one.

Code:
var results = /<row>(.+?)<\/row>/g;
var tableRows = results.exec('<row>word1</row><row>word2</row><row>word3</row>');
alert(tableRows.length);
 
[tt]var results = /<row>(.+?)<\/row>/g;
var s="<row>word1</row><row>word2</row><row>word3</row>";
var tableRows = s.match(results)
alert(tableRows.length);
if (tableRows) {
for (var i=0;i<tableRows.length);i++) {
alert(tableRows.replace(results,"$1");
}
}
[/tt]
 
Thanks for the tips, guys. I'll probably end up using one of those, but I'm still confused about why therer isn't a better way. Shouldn't the global flag match every word?
 
[1] I had an obvious typo in my post.
[tt]for (var i=0;i<tableRows.lengt[highlight]h);[/highlight]i++) {[/tt]

[2] The global flag is just fine. The only problem is that methods are not intuitive. You have to read the fine print of the documentation.
regexp::exec method
string::match method

[3] If you want to stick to regexp::exec method, which I find no objection at all and that it may even be better, you have to loop until tableRows return null (here, the global flag still plays an important role.) Like this.
[tt]
var results = /<row>(.+?)<\/row>/g;
var tableRows;
do {
tableRows = results.exec('<row>word1</row><row>word2</row><row>word3</row>');
if (tableRows) {
alert(tableRows[1]); //index 1 contains the backreference
}
} while (tableRows)
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top