Regular expression (javascript) How to match any two tags any number of times

I am trying to find all occurrences of elements in an HTML page that are between the <nobr>

and tags </nobr>

. EDIT: (nobr is an example. I need to find content between random lines, not always tags)

I tried this

var match = /<nobr>(.*?)<\/nobr>/img.exec(document.documentElement.innerHTML);
alert (match);

      

But this only gives one entry. + it appears twice, once with tags <nobr></nobr>

and once without them. I only want the untagged version.

+1


a source to share


6 answers


you need to do it in a loop



var match, re = /<nobr>(.*?)<\/nobr>/img;
while((match = re.exec(document.documentElement.innerHTML)) !== null){
   alert(match[1]);
}

      

+5


a source


use the DOM

var nobrs = document.getElementsByTagName("nobr")

      



and then you can skip all nobrs and extract innerHTML or apply any other action to them.

+5


a source


(Since I cannot comment on Rafael's correct answer ...)

exec

does what it should do - find the first match, return the result to the object, match

and set up for the next call exec

. The object match

contains (at index 0) the entire string matched by the entire regular expression. Subsequent slots contain the bits of the string, matched by parentheses in parentheses. So, match[1]

contains the bit of the string associated with "(. *?)" In your example.

+2


a source


you can use

while (match = /<nobr>(.*?)<\/nobr>/img.exec("foo <nobr> hello </nobr> bar <nobr> world </nobr> foobar"))
    alert (match[1]);

      

+1


a source


If the strings you are using are not xml elements and you are sticking with regexes, the return value you get can be bracketing explained .. exec returns the entire match string followed by the contents of the expressions in parentheses.

If your document contains:

This is out. 
Bzz. This is in. unBzz.

then

/Bzz.(.*?)unBzz./img.exec(document.documentElement.innerHTML)

Gives you Bzz. This is in. UnBzz. 'at element 0 of the returned array and "This is". in element 1. Trying to display the entire array gives both a comma separated list and one that JavaScript does to try to display it.

So alert($match[1]);

this is what you need.

+1


a source


steps are required, but you can do it like this

match = document.documentElement.innerHTML.match(/<nobr>(.*?)<\/nobr>/img)
alert(match)//includes '<nobr>'

match_length = match.length;
for (var i = 0; i < match_length; i++)
{
    var match2 = match[i].match(/<nobr>(.*?)<\/nobr>/im);//same regex without the g option
    alert(match2[1]);
}

      

+1


a source







All Articles