var s = 'abcjkjokabckjk'
search = 'abc'
var n = 2
alert(s.replace(RegExp("^(?:.*?abc){" + n + "}"), function(x){return x.replace(RegExp(search + "$"), "HHHH")}))
const replace_nth = function (s, f, r, n) {
// From the given string s, find f, replace as r only on n’th occurrence
return s.replace(RegExp("^(?:.*?" + f + "){" + n + "}"), x => x.replace(RegExp(f + "$"), r));
};
这里有一个例子。
$node
Welcome to Node.js v13.1.0.
Type ".help" for more information.
>
> const replace_nth = function (s, f, r, n) {
... // From the given string s, replace f with r of nth occurrence
... return s.replace(RegExp("^(?:.*?" + f + "){" + n + "}"), x => x.replace(RegExp(f + "$"), r));
...};
> replace_nth('hello world', 'l', 'L', 1)
'heLlo world'
var string = 'abcde|abcde|abcde|abcde',
needle = 'abc',
firstIndex = string.indexOf(needle),
lastIndex = string.lastIndexOf(needle);
// ----------------------------------------------------------------
// Remove first occurence
var first = string.substring(0, firstIndex) + '***' + string.substring(firstIndex + needle.length);
document.getElementById('first').innerHTML = first;
// ----------------------------------------------------------------
// Remove last occurence
var last = string.substring(0, lastIndex) + '***' + string.substring(lastIndex + needle.length);
document.getElementById('last').innerHTML = last;
// ----------------------------------------------------------------
// Remove nth occurence
// For Demo: Remove 2nd occurence
var counter = 2, // zero-based index
nThIndex = 0;
if (counter > 0) {
while (counter--) {
// Get the index of the next occurence
nThIndex = string.indexOf(needle, nThIndex + needle.length);
}
// Here `nThIndex` will be the index of the nth occurence
}
var second = string.substring(0, nThIndex) + '***' + string.substring(nThIndex + needle.length);
document.getElementById('second').innerHTML = second;
4条答案
按热度按时间vltsax251#
使用
RegExp
构造函数在正则表达式中传递变量。d6kp6zgx2#
使用RegExp模块创建如下函数
这里有一个例子。
ctehm74n3#
这可以在没有RegEx的情况下完成。
字符串方法
String#indexOf
、String#lastIndexOf
可以与String#substring
一起使用iqxoj9l94#