在窗口对象中有字符串.find()的等价项吗



所以我知道window.find((,一个在页面上查找字符串的非标准js对象,如果找到,它将返回true,如果没有找到,则返回false。现在是否有类似于string.replacement((的东西,但是否有一个窗口对象(例如:window.replacement(会将所有并发元素替换为其他东西(例如,将所有"Hi"替换为"Hello"(?

我认为没有,但它比您可能怀疑的更容易编写。您只需在DOM中查找Text节点,并在它们的nodeValue:上使用replace

function replaceAll(element, regex, replacement) {
for (var child = element.firstChild;
child;
child = child.nextSibling) {
if (child.nodeType === 3) { // Text
child.nodeValue = child.nodeValue.replace(regex, replacement);
} else if (child.nodeType === 1) { // Element
replaceAll(child, regex, replacement);
}
}
}

在那里,我使用了一个正则表达式(它需要有g标志(来获得执行替换时的"全局"行为,并具有灵活性。

实例:

function replaceAll(element, regex, replacement) {
for (var child = element.firstChild;
child;
child = child.nextSibling) {
if (child.nodeType === 3) { // Text
child.nodeValue = child.nodeValue.replace(regex, replacement);
} else if (child.nodeType === 1) { // Element
replaceAll(child, regex, replacement);
}
}
}
setTimeout(function() {
replaceAll(document.body, /one/g, "two");
}, 800);
<div>
Here's one.
<p>And here's one.</p>
<p>And here's <strong>one</strong>
</div>

如果你想使用一个简单的字符串而不是正则表达式,只需使用一个正则表达式转义函数(比如这个问题的答案中的函数(,并像这样构建你的正则表达式:

var regex = new RegExp(yourEscapeFunction(simpleString), "g");

这不处理的情况是目标字符串穿过文本节点的地方,如下所示:

<span>ex<span>ample</span></span>

使用上面的函数查找"example",你不会找到它。我把它作为一个练习,让读者根据需要处理这种情况…:-(

最新更新