javascript - 替换文本,但忽略文档中的某个字符串

标签 javascript regex

我有一个大字符串:Hello <span class="ashakd">my</span> name is <bob>!

我有第二个字符串:llo my name

我有我想要替换它的内容:<span class="ashakd">llo my name</span>

我需要replace()就好像 <span class="ashakd"></span>不存在,但它们被替换为字符串,因此最终结果是: He<span class="ashakd">llo my name</span> is <bob>!

PS:<bob>存在,因此您不能忽略两个 > 之间的任何文本,它必须专门忽略 <span class="ashakd"></span>

如果这令人困惑,非常抱歉。如果这令人困惑,请让我说得更清楚

编辑

很抱歉不清楚,但它只能替换我的替换范围内的内容。所以如果原始字符串是: Hello <span class="ashakd">my</span> name is <bob><span class="ashakd">hello</span>!

结果将是:He<span class="ashakd">llo my name</span> is <bob><span class="ashakd">hello</span>!

最佳答案

这可能对原始字符串破坏性太大,但我建议这个解决方案:

var a = 'Hello <span class="ashakd">my</span> name is <bob>!';
var searchString = 'llo my name';
// remove all <span> and </span> tags,  you may not want to remove any and all span tags???
a = a.replace(/<\/?span[^>]*?>/g,'');
a = a.replace(searchString,"<span class='ashakd'>"+searchString+"</span>");

它的作用是删除所有 span 标签,然后搜索“llo my name”搜索字符串,并用 span 标签将其包装起来。

既然你说你不太了解正则表达式,那么这里有一个描述:

/<\/?span[^>]*?>/g

<\/?   means match on '<' and then optionally a /.  This matches both the start and end tags, i.e. <span...> and </span>

[^>]*?  means match any character that is NOT > in a non-greedy fashion, i.e. stop matching at the first > found.

The final /g means 'global', which means match <span> and </span> as many times as possible.

关于javascript - 替换文本,但忽略文档中的某个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23742314/

相关文章:

javascript - 使用 AngularJS 获取 HTML 元素的 id

javascript - 使用 CSS 媒体查询选择 JavaScript 元素

JavaScript 正则表达式。在字符串中查找重要的单词和名称

regex - 如何在正则表达式中检测各种连字符、减号和破折号?

json - 如何将双引号中的内容与 golang 中的正则表达式进行匹配?

javascript - 从 javascript 对象键创建对象数组

javascript - 如何通过过滤获取的数据来更新状态?

javascript - 如何使用 getElementById 检查长度

javascript - 正则表达式 Camel 化字符串中的特定文本

regex - 用于在 HTTP url 中检索文件扩展名的正则表达式