我正在尝试使用 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"));
<span class="myclass"> span text </span>
此正则表达式仅在search="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>
*本主题应该可以帮助任何寻求匹配并替换匹配字符串的人,同时避免被特定字符包围的字符串被替换。