Dhanan
Dhanan

Reputation: 207

Javascript Multiline regualr expression

I Want to match the content start with the tag and ends with the tag

i have used match(/\<block\>(.*)\<\/block>/g);

But its only works for one line <block>Data</block>

Not for others

 <block>Data 
   can be here 
   </block>

Any suggestions please

Upvotes: 1

Views: 75

Answers (2)

anubhava
anubhava

Reputation: 785128

Javascript doesn't have DOTALL flag in its regex engine.

But Javascript way to make dot match newlines is:

string.match(/<block>([\s\S]*?)<\/block>/ig);

[\s\S] in place of . matches any character including newlines.

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You must replace the dot . by [\s\S] because the dot doesn't match newlines.

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

An alternative is to use [^<]* if no other tags are nested:

/<block>([^<]*)<\/block>/g

However a code like this:

<block> abcd
    <block>efgh</block>
</block>

will fail with the first pattern, and you can't solve the problem with javascript regexes.

Upvotes: 1

Related Questions