gpt4 book ai didi

javascript - 在 JavaScript 中任意替换出现的事件

转载 作者:行者123 更新时间:2023-11-30 10:06:09 25 4
gpt4 key购买 nike

我正在使用 replace() 方法 来突出显示句子中的某些单词。默认情况下,该方法仅替换第一次出现的目标词。我想知道如何执行任意替换。例如:在一种情况下替换第 2 次出现的单词,在另一种情况下替换第 1 次和第 3 次出现的单词,另一种情况下替换第 2 次和第 3 次出现的单词,依此类推。下面,句子中出现了 3 次“上面”:

var stc = 'above of the limit of reason, above of the capacity of the brain, above all.'
var wrd = 'above'; // target-word
var rpl = new RegExp ("\\b" + wrd + "\\b");
var wrd_subs = '<span class="myclass">above</span>'; // stylized word.
var ocr = 2; // occurrence(s).

stc = stc.replace(rpl, wrd_subs); // normal replacement.

想法是如果变量的值执行“正常”替换 ocr false,但如果值为 2,例如,仅应替换第 2 次出现。正如我之前提到的,我还想在同一个变量中一次提供所有事件。 eg:给定var ocr = 2-3(当然可能不会这么写!),替换第2和第3个出现的地方,给定var ocr = 1,3 >,替换第 1 次和第 3 次出现。解决方案最好使用 replace() 方法,但我对其他想法持开放态度。

最佳答案

您可以使用带有 g 标志的替换回调(替换多次出现),然后根据计数器和您的其他状态使用替换文本或原始文本进行响应。

为了确定要替换的匹配序列,您可以传递一个计数数组。因此,要替换第二个和第三个匹配项,您需要传递 [1,2](因为匹配项是从零开始的)。

参见 MDN description替换回调的工作原理。


这是一个想法的演示:http://jsfiddle.net/jfriend00/n0yejpnv/

var stc = 'above of the limit of reason, above of the capacity of the brain, above all.'

function replaceN(str, regex, replace, occurrencesArray) {
var cntr = 0;
return str.replace(regex, function(match) {
var replacement;
if (!occurrencesArray || occurrencesArray.indexOf(cntr) !== -1) {
replacement = replace;
} else {
replacement = match;
}
++cntr;
return replacement;
});
}

// replace only the second occurrence of "the" with "THE"
console.log(replaceN(stc, /the/g, "THE", [1]));

// replace the first and thirds occurrences of "above" with "Above"
console.log(replaceN(stc, /above/g, "ABOVE", [0,2]));

关于javascript - 在 JavaScript 中任意替换出现的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29057223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com