简体   繁体   English

删除字符串中的特定html标签-javascript

[英]removing specific html tags in a string - javascript

I'm trying to clean up a string of text on the server side from the output generated by a wysiwyg. 我正在尝试从所见即所得生成的输出中清除服务器端的字符串。 and while I can fix it client side, it's best to also fix this on the server side. 虽然我可以在客户端进行修复,但最好也在服务器端进行修复。

var string = "<p>firstline</p><p>secondline</p><p>thirdline</p><p>iframe</p><p>a</p><p>df</p><p>dsf&nbsp;</p><p><br></p><p>sd</p><p>f</p><p>sdf</p><p><br></p>"

var x = string.replace("<p><br></p>", "");

https://jsfiddle.net/8c0yh9r7/ https://jsfiddle.net/8c0yh9r7/

the code should but doesn't get rid of the break within the paragraphs 代码应该但不会摆脱段落中的中断

why is that? 这是为什么?

Use a regex with a global flag, like: 使用带有全局标志的正则表达式,例如:

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

https://jsfiddle.net/Lu2r3820/1/ https://jsfiddle.net/Lu2r3820/1/

When using a string only the first occurrence will be replaced. 使用字符串时,只会替换第一个出现的字符串。

See replace() documentation 请参阅replace()文档

doesn't get rid of the break within the paragraphs 没有摆脱段落中的中断

Yes, it does… but only once . 是的,它确实……但仅一次 You have more than one paragraph containing a line break in your code. 您有多个段落在代码中包含换行符。

If you want to replace it more than once, you need to use a regex and mark it as global with g . 如果要多次替换它,则需要使用一个正则表达式并用g将其标记为global。

var x = string.replace(/<p><br><\/p>/g, "");

It does replace, but only the first occurrence. 它确实代替了,但仅是第一次出现。 If you run this afterwards, you can see the second occurrence disappearing. 如果此后运行,则可以看到第二个事件消失了。

var x = x.replace("<p><br></p>", "");

refer to this to replace all occurrences. 请参考此内容以替换所有出现的情况。 How to replace all occurrences of a string in JavaScript? 如何替换JavaScript中所有出现的字符串?

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

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