我用replace() method来突出句子中的某些单词。默认情况下,该方法只替换目标单词的第一次出现。我想知道如何执行任意的替换。例:在一种情况下替换单词的第二次出现,在另一种情况下替换第一次和第三次,另一次替换第二次和第三次,等等。在下面的句子中,有三处出现“以上”一词:
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,则应该只替换第二次出现。我还希望,正如我前面提到的,如果可能的话,在同一变量中同时提供中的所有事件。例句:给定var ocr = 2-3 (当然,它可能不是这样写的!),替换第二次和第三次,给var ocr = 1,3替换第一次和第三次。最好是,解决方案应该使用replace() method,但我对其他想法持开放态度。
发布于 2015-03-15 04:28:03
您可以使用带有g标志的替换回调(以替换多次出现),然后根据计数器和其他状态使用替换文本或原始文本进行响应。
为了确定要替换的匹配序列,可以传递一个计数数组。因此,要替换第2和第3匹配,您可以传递[1,2] (因为匹配是基于零的)。
有关它的工作方式,请参阅替换回调的MDN描述。
下面是这个想法的演示: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])); https://stackoverflow.com/questions/29057223
复制相似问题