我有一个大字符串: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/