我正在使用replace() method
来突出显示句子中的某些字词。默认情况下,该方法仅替换第一次出现的目标字。我想知道如何 执行任意替换 。例:在一种情况下替换第二次出现的单词,在另一种情况下替换第一次和第三次出现,另一次取代第二次和第三次,依此类推。下面,该句子包含3个出现的单词“above”:
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
<,则 执行“正常”替换/ strong> false
,但如果值为2,则应仅替换第2次出现。我还想,如前所述,如果可能的话, 在同一个变量中同时提供所有出现 。例如:给定var ocr = 2-3
(当然它可能不是那样写的!),替换第2次和第3次出现,给定var ocr = 1,3
,替换第1次和第3次出现。优选地,解决方案应该使用replace() method
,但我对其他想法持开放态度。
答案 0 :(得分:4)
您可以使用带有g
标记的替换回调(以替换多次出现),然后根据计数器和您的其他状态使用替换文本或原始文本进行响应。
要确定要替换的匹配项,您可以传递一组计数。因此,要替换第2和第3个匹配,您将传递[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]));