[英]Regex to match html comments, in javascript
我需要一个 javascript 中的正则表达式,它替换字符串中所有出现的<!-- foo -->
。
我试过:
thestring.replace(/<!--[\s\S]*-->/gm, "")
但这不起作用,甚至破坏了我的文字。
我不能使用.*
因为它不包括换行符。
示例多行注释:
<!-- foo
bar
baz-->
尝试:
thestring.replace(/<!--[^]*-->/gm, "")
或使用懒惰?
使前一个量词找到最短的匹配:
thestring.replace(/<!--[^]*?-->/gm, "")
^
<!-- a comment here --> oops, ignore? -->
^^^^^^^^^^^^^^^^^^^^^^^
作为旁注,如果您尝试使用 regexp 解析 html,我建议您查看此处的最佳答案: RegEx match open tags except XHTML self-contained tags
试试这个: /<!--[\\w\\s]+-->/g
const re = /<!--[\w\s]+-->/g
const str = 'test <!-- foo --> abc'
console.log(str.replace(re, ''))
编辑:OP 的代码看起来不错?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.