Home > Article > Web Front-end > How to Effectively Use Regex in JavaScript for Multiline Matching?
Utilizing Regex in JavaScript Across Multiple Lines
In JavaScript, the 'm' flag, supposedly designed for multiline matching, fails to capture content spanning across newlines. To resolve this, a more robust solution is required.
The key is to employ either '[sS]' or '[^]' as the multiline dot. These patterns match any character, including newlines. This approach effectively captures content regardless of its distribution over multiple lines.
Example:
var ss = "<pre class="brush:php;toolbar:false">aaaa\nbbb\ncccddd"; var arr = ss.match( /
[\s\S]*?<\/pre>/gm ); console.log(arr); // Outputs: `<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc`
Less Cryptic Alternative:
While the provided solution is effective, a less intricate approach can be achieved by replacing '[sS]' with '.*?'. This quantifier matches any number of characters (including newlines) non-greedily, resulting in more efficient and targeted matching.
var arr = ss.match( /<pre class="brush:php;toolbar:false">.*?<\/pre>/gm ); console.log(arr); // Outputs: `<pre class="brush:php;toolbar:false">aaaa\nbbb\nccc`
Tips:
The above is the detailed content of How to Effectively Use Regex in JavaScript for Multiline Matching?. For more information, please follow other related articles on the PHP Chinese website!