简体   繁体   English

Javascript 正则表达式替换结束标签和开始标签

[英]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!忽略它不是很好的事实 html,不过这对我来说很有意义!

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. replace返回一个带有结果的新字符串,它不会修改您调用它的字符串。 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/您的代码工作正常: http://jsfiddle.net/eBkhR/

Strings in javascript are immutable. javascript 中的字符串是不可变的。 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.因此,当使用replace方法时,它不能替换内容,而只是返回一个带有新内容的新字符串。 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.带有alert的答案将起作用,因为新字符串正在传递给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 标签中都有 id,所以只需要搜索这个:

/<\/p><p/g

Thanks for all the replies though!感谢所有的回复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM