How to ignore newline in regexp?

By reading this one: How to use JavaScript regex over multiple lines?

I came with that, which works:

var data = "<test>11\n1</test>\n#EXTM3U\n";
reg = /<test>([\s\S]*?)<\/test>/;
var match = data.match(reg);
console.log(match[1]);

Here is a fiddle: http://jsfiddle.net/Rpkj2/


In JavaScript, there is no flag to tell to RegExp() that . should match newlines. So, you need to use a workaround e.g. [\s\S].

Your RegExp would then look like this:

var reg = new RegExp( "\<" + "test" + "\>([\s\S]*?)\<\/" + "test" + "\>" );

You are missing a JS newline character \ at the end of line 2.

Also, change regexp to:

 var data = "\
    <test>11\n\
    1</test>\n\
    #EXTM3U\n\
 ";
 var reg = new RegExp(/<test>(.|\s)*<\/test>/);
 var match = data.match(reg);
 console.log(match[0]);

http://jsfiddle.net/samliew/DPc2E/

Tags:

Javascript