简体   繁体   中英

Extract script tags from a HTML string

Or any other tags :)

for eg.

  <head>
    <title>page...</title>
    <script> var a = 'abc'; </script>
    <script src="foo.js" type="text/javascript"></script>
  </head>
  <body>
    ...
    <script src="foo2.js"></script>
  </body>

(this string is a response from a ajax call)

I want to get a array with 3 strings:

  1. <script> var a = 'abc'; </script>
  2. <script src="foo.js" type="text/javascript"></script>
  3. <script src="foo2.js"></script>

How can I do that?

Define: outerHTML function (taken from here )

jQuery.fn.outerHTML = function(s) {
return (s) ? this.before(s).remove() : jQuery("&lt;p&gt;").append(this.eq(0).clone()).html();
}

Then assume your response is stored in data you can do:

$(data).filter("script").each( function(e) { 
    // do something with $(e).outerHTML()
} );

使用带有<script[^<]*</script>模式的正则表达式。

You can try something like:

 function getScriptsAsText() {
   var div = document.createElement('div');
   var scripts = [];
   var scriptNodes = document.getElementsByTagName('script');

   for (var i=0, iLen=scriptNodes.length; i<iLen; i++) {
     div.appendChild(scriptNodes[i].cloneNode(true));
     scripts.push(div.innerHTML);
     div.removeChild(div.firstChild);
   }
   return scripts;
 }

It returns a array of the current script elements as text, including their start and end tags.

You might also try outerHTML, but it's not that widely supported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM