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

时间:2014-05-19 16:02:09

标签: 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>存在,因此您无法忽略两个&gt;之间的任何文字,它必须明确忽略<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>!

1 个答案:

答案 0 :(得分:1)

这可能对原始字符串过于具有破坏性,但我提出了这个解决方案:

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标签,然后搜索你的姓名&#34; llo我的名字&#34;搜索字符串,并用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.