Amyth
Amyth

Reputation: 32949

javascript regex, replace multiple instances with a single one in multiline string

I have a multi-line string in javascript as follows:

"<p> </p>
<p> </p>
<p> </p>
<p> </p>
"

I am trying to remove the extra instances of <p> </p>, so I am trying to use the following regex.

var content = getContent() // This returns the string mentioned above.
content = content.replace(/(<p> <\/p>)+/g, "<p> <\/p>");

But this does not seem to work. Most probably because the string is a multi-line string ? I have tried the above regex with a single line string and it works fine. After reading a little more documentation about javascript regex, I realized that we need to use the m modifier to deal with multi-line strings. So I changed the regex to:

content = content.replace(/(<p> <\/p>)+/gm, "<p> <\/p>"); // note the `m` modifier

But it still does not work. any clues ?

Upvotes: 3

Views: 463

Answers (2)

anubhava
anubhava

Reputation: 785156

se this replace:

content = content.replace(/(<p> +<\/p>\n*)+/g, "<p> </p>");
/=> <p> </p>

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You should replace all spaces (including new lines) :

content = content.replace(/(<p>\s*<\/p>\s*)+/g, "<p> <\/p>");

Demonstration

Upvotes: 2

Related Questions