WastedSpace
WastedSpace

Reputation: 1143

Javascript regex replace between closing and opening tags

I realise this must be a really easy piece of regex, but just can't seem to work it out. I just need to search a string for this:

</p><p>

And add a comma between them, like this:

</p>,<p>

Ignore the fact it isn't nice html, it makes sense to me though!

I tried this, but didn't seem to work:

str.replace(/<\/p><p>/g, "</p>,<p>");

Any ideas? Thanks :)

Upvotes: 0

Views: 2728

Answers (5)

WastedSpace
WastedSpace

Reputation: 1143

My fault. It does work. I'd forgotten that I have ids in each p tag, so just needed to search for this:

/<\/p><p/g

Thanks for all the replies though!

Upvotes: 0

sv_in
sv_in

Reputation: 14049

Strings in javascript are immutable. That is, the contents in a string cannot be modified. Therefore, when using replace method it cannot replace the content but it just returns a new string with the new contents. You would need to store the new string the in required variable.

for example,

str = str.replace(/<\/p><p>/g, "</p>,<p>");

The answers with alert will work because the new string is getting passed to the alert function. The string itself is not modified.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075139

I tried this, but didn't seem to work:

str.replace(/<\/p><p>/g, "</p>,<p>");

replace returns a new string with the result, it doesn't modify the string you called it on. So that would be:

    str = str.replace(/<\/p><p>/g, "</p>,<p>");
//  ^^^^^^

Upvotes: 2

Qtax
Qtax

Reputation: 33918

Your code works just fine: http://jsfiddle.net/eBkhR/

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93060

This works for me:

alert("Some </p><p> to replace".replace(/<\/p><p>/g, "</p>,<p>"));

Upvotes: 0

Related Questions