CME*_*E64 1 html javascript regex tags string
我正在尝试使用JS来替换包含html标签+属性和样式的字符串中的特定字符串,同时避免标签的内侧被读取或匹配(并保留文本中的原始标签).
例如,我想<span> this is span text </span>成为:<span> this is s<span class="found">pan</span> text </span>当关键字是"pan"时
我尝试使用正则表达式..到目前为止我的正则表达式:
$(this).html($(this).html().replace(new RegExp("([^<\"][a-zA-Z0-9\"'\=;:]*)(" + search + ")([a-zA-Z0-9\"'\=;:]*[^>\"])", 'ig'), "$1<span class='found'>$2</span>$3"));
Run Code Online (Sandbox Code Playgroud)
这种正则表达式仅在<span class="myclass"> span text </span>搜索="p"时才会失败,结果如下:
<s<span class="found">p</span>an class="myclass"> s<span class="found">p</span>an text</s<span class="found">p</span>an>
Run Code Online (Sandbox Code Playgroud)
*此主题应该帮助任何寻求匹配并替换匹配字符串的人,同时避免被特定字符包围的字符串替换.
不要使用带有html的正则表达式,遍历并操纵DOM:
doc = $('<div><span class="myclass"> span text </span></div>')
$(doc).find("*").andSelf().contents().each(function() {
if(this.nodeType == 3)
$(this).replaceWith($(this).text().replace(/p/g, "<b>p</b>"))
})
console.log(doc.html())
// <span class="myclass"> s<b>p</b>an text </span>
Run Code Online (Sandbox Code Playgroud)
如果你坚持使用正则表达式,它会像这样:
text = '<span class="myclass"> <p>span</p> </span>'
found = 'p'
re = new RegExp(found + '(?=[^<>]*(<|$))', 'g')
text = text.replace(re, "<b>$&</b>")
console.log(text)
// <span class="myclass"> <p>s<b>p</b>an</p> </span>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3239 次 |
| 最近记录: |