Extract script tags from a HTML string

前端 未结 3 1853
我寻月下人不归
我寻月下人不归 2021-02-14 03:51

Or any other tags :)

for eg.

  
    page...
    
    

        
相关标签:
3条回答
  • 2021-02-14 04:31

    Define: outerHTML function (taken from here)

    jQuery.fn.outerHTML = function(s) {
    return (s) ? this.before(s).remove() : jQuery("<p>").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()
    } );
    
    0 讨论(0)
  • 2021-02-14 04:33

    Use a regular expression with the pattern <script[^<]*</script>.

    0 讨论(0)
  • 2021-02-14 04:36

    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.

    0 讨论(0)
提交回复
热议问题