Javascript regex replace between closing and opening tags
I realise this must be a really easy piece of regex, but jus开发者_JS百科t 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 :)
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>");
// ^^^^^^
This works for me:
alert("Some </p><p> to replace".replace(/<\/p><p>/g, "</p>,<p>"));
Your code works just fine: http://jsfiddle.net/eBkhR/
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.
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!
精彩评论