Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript RegExp: how to match multiline and closetag

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 got wrong script: var x=0;</script><div>..</div><script>var y=0;

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

like image 614
guilin 桂林 Avatar asked Nov 28 '22 18:11

guilin 桂林


1 Answers

Use regex like below:

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

In Javascript we cannot make . dotall so we use the [\s\S] character class which matches any character either whitespace or not whitespace including newline. ? is for non-greedy match so that you don't nest script tags.

like image 80
manojlds Avatar answered Dec 06 '22 09:12

manojlds