Javascript RegExp: how to combine multi-line and private

var ex = /(<script\s?[^>]*>)([\s\S]*)(<\/script>)/; //Note: here is 2 script tags var str = '<script>\nvar x=0;\n</script>\n<div>\nhtml\n</div>\n<script>var y=0;\n</script>' str.replace(ex, function(full, prefix, script, suffix) { return prefix + doSomething(script) + suffix; }) 

But I was mistaken the script: var x=0;</script><div>..</div><script>var y=0;

I want: var x=0; and var y=0;

+4
source share
2 answers

Use a regex as shown below:

 <script>([\s\S]*?)</script> 

In javascript we can not do . dotall, so we use the character class [\ s \ S], which matches any space or space character, including a new line. ? for non-greedy matching, so you don't embed script tags.

+20
source

This function matches the contents of the SCRIPT elements and returns the rows in the array:

 // Return an array of <script> elements contents. function getScriptsConntents(text) { var scripts = []; var m; var re = /<script[^>]*>([\s\S]*?)<\/script>/ig; while (m = re.exec(text)) { scripts.push(m[1]); } return scripts; } 
+3
source

All Articles