1

我正在尝试使用 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>

*本主题应该可以帮助任何寻求匹配并替换匹配字符串的人,同时避免被特定字符包围的字符串被替换。

4

1 回答 1

4

正如 thg435 所说,处理 html 内容的好方法是使用 DOM。

但是如果你想在替换中避免某些东西,你可以先匹配你想避免的东西,然后自己替换它。

避免使用 html 标签的示例:

var text = '<span class="myclass"> span text </span>';

function callback(p1, p2) {
    return ((p2==undefined)||p2=='')?p1:'<span class="found">'+p1+'</span>';
}

var result = text.replace(/<[^>]+>|(p)/g, callback);

alert(result);
于 2013-05-17T09:15:18.473 回答