Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new RegExp vs. /pattern/ and multi line

Why is the /pattern/ matching, but the RegExp not?

<div id="foo">
##content##
<h1>works!</h1>
##/content##
</div>

<script>
var str = document.getElementById("foo").innerHTML;
console.log(str);

var r = new RegExp("##content##([\S\s]*)##\/content##", "img");

console.log(r.exec(str)); //null
console.log(str.match(/##content##([\S\s]*)##\/content##/img)); //matches
</script>
like image 365
David Müller Avatar asked Feb 16 '26 19:02

David Müller


1 Answers

Problem is this line:

var r = new RegExp("##content##([\S\s]*?)##\/content##", "img");

It should be replaced with:

var r = new RegExp("##content##([\\S\\s]*?)##\/content##", "img");

Reason: Understand that RegExp object takes a String as argument to construct and you need to double escape \S and \s to be correctly interpreted by RegEx engine so \S should become \\S and \s should become \\s in your regex.

like image 193
anubhava Avatar answered Feb 18 '26 07:02

anubhava