How to get a regex to match multiple script tags?

I am trying to return the contents of any tags in the text. I am currently using the following expression, but it only captures the contents of the first tag and then ignores the others.

Here's a sample html:

    <script type="text/javascript">
        alert('1');
    </script>

    <div>Test</div>

    <script type="text/javascript">
        alert('2');
    </script>

My regex looks like this:

//scripttext contains the sample
re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts  = re.exec(scripttext);

When I run this in IE6, it returns 2 matches. The first contains the full tag, the second contains the warning ('1').

When I run it at http://www.pagecolumn.com/tool/regtest.htm , it gives me 2 results, each of which contains only script tags.

+5
source share
6 answers

"" , exec. , (.. ) lastIndex . , , ( ):

var scripttext = ' <script type="text/javascript">\nalert(\'1\');\n</script>\n\n<div>Test</div>\n\n<script type="text/javascript">\nalert(\'2\');\n</script>';

var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;

var match;
while (match = re.exec(scripttext)) {
  // full match is in match[0], whereas captured groups are in ...[1], ...[2], etc.
  console.log(match[1]);
}
+28

HTML. HTML . DOM. , .

var scripts = document.getElementsByTagName('script');
+3

:

document.body.innerHTML.match(/<script.*?>([\s\S]*?)<\/script>/gmi)

: ( ).

+2

.

: ? :

re = "/<script\b[^>]*>([\s\S]*?)<\/script>/gm";
0

.Net PHP, preg_match_all, . Javascript . .

http://www.pagecolumn.com/tool/regtest.htm

$1elements ,

0

for each(var x in document.getElementsByTagName('script');
     if (x && x.innerHTML){
          var yourRegex = /http:\/\/\.*\.com/g;
          var matches = yourRegex.exec(x.innerHTML);
             if (matches){
          your code
 }}
0

All Articles