例如:
'abcjkjokabckjk'.replace('/(abc)/g',...)
如果我想替换指定位置'abc',我能做什么?
像这样:
答案 0 :(得分:6)
使用RegExp
构造函数在regex中传递变量。
var s = 'abcjkjokabckjk'
search = 'abc'
var n = 2
alert(s.replace(RegExp("^(?:.*?abc){" + n + "}"), function(x){return x.replace(RegExp(search + "$"), "HHHH")}))
答案 1 :(得分:2)
这可以在没有RegEx的情况下完成。
字符串方法String#indexOf
,String#lastIndexOf
可与String#substring
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;

table tr td:nth-child(2) {
color: green;
}
td {
padding: 15px;
}

<table border="1px">
<tr>
<td>After replacing <strong>first</strong> occurence:</td>
<td id="first"></td>
</tr>
<tr>
<td>After replacing <strong>last</strong> occurence:</td>
<td id="last"></td>
</tr>
<tr>
<td>After replacing <strong>2nd<sup>zero-based index</sup></strong> occurence:</td>
<td id="second"></td>
</tr>
</table>
&#13;
答案 2 :(得分:1)
在RegExp构造函数中使用Avinash的方法
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));
};
这是一个例子。
$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'