我需要在特定标签内部进行更改。
例如,
"this is first <a>this is second</a> this is third"
在这里,我想找到第二个“是”。我可以在/(<a)[\S\s]*?(<\/a>)/gi
之间找到全文,但我不知道如何在这个正则表达式中找到“是”
答案 0 :(得分:0)
我建议不在这里使用正则表达式,因为问题有点过于复杂,而且使用正则表达式可能会使用正则表达式它不会很漂亮而你可能会错过一些边缘情况。
所以,我就是这样做的
var input = "this is first <a>this is second</a> this is third";
//this isn't truly using a regex - it's a very small part of the solution, hence a very small regex. It will match any word "is" but not "this"
var regex =/\bis\b/ig;
//this is a new unattached element that will be used to leverage the DOM parsing of the browser
var scratchPad = document.createElement("div");
//this will set the content of the <div> tag and it will be parsed as HTML
scratchPad.innerHTML = input;
//no need to parse the tags manually - we can just do it like this
var allTags = Array.from(scratchPad.getElementsByTagName("a"));
//iterate and modify the elements in place
allTags.forEach(function(el) {
el.innerHTML = el.innerHTML.replace(regex, "!FOO!")
});
//see the results
console.log(scratchPad.innerHTML);
&#13;
这很冗长,但它是为了说明会发生什么。
这是一个更实际的例子,说明如何使用
function replacer(input, replaceWhat, replaceWith, inTag) {
var regex = new RegExp("\\b" + replaceWhat + "\\b", "ig");
var scratchPad = document.getElementById("_replacingDiv");
//if not there, create it and attach it, so it's available next time
if (!scratchPad) {
scratchPad = document.createElement("div");
scratchPad.id = "_replacingDiv";
scratchPad.hidden = true;
document.body.appendChild(scratchPad);
}
scratchPad.innerHTML = input;
var tags = scratchPad.getElementsByTagName(inTag);
Array.prototype.forEach.call(tags, function(el) {
el.innerHTML = el.innerHTML.replace(regex, replaceWith);
});
return scratchPad.innerHTML;
}
var inputSimple = "this is first <a>this is second</a> this is third";
var inputComplex = "this is first <a>this is second</a> \n"+
"this is third <a>this is fourth</a> \n"+
"this is fifth <a>no match sixth</a> \n"+
"this isn't matched seventh <a>this isn't matched eighth</a> \n"+
"mutltiple is is example ninth <a>multiple is is example tenth </a>";
console.log(replacer(inputSimple, "is", "!FOO!", "a"));
console.log(replacer(inputComplex, "is", "!FOO!", "a"));
&#13;
这应该不作为函数的最终形式,但是从这里开始,您可以根据自己的需要进行定制。以下是一些可能需要更改的内容:
scratchPad
,这样可以防止任何恶意代码被运行。但是,您仍然需要安全地处理输出。foo
中的每个span
,但该标记包含嵌套的a
。如果是这种情况,由您来决定究竟会发生什么 - 是否会考虑或跳过内部标记。请注意,如果有<a class="foo">