例如:有一个字符串为“hello world hello,it’s a brand new world”,现要替换第二个“hello”为“!”
只能想到一个笨办法。
function replace(str,n,so,s){
let d=0;
r=RegExp(so,"g")
return str.replace(r,m=>{
d++;
if(d==n){
return s
}
return m
});
}
console.log(replace("hello world hello,it's a brand new world",2,"hello","!"))
//hello world !,it's a brand new world