替换字符串中出现的第n个词

例如:有一个字符串为“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
发布了3 篇原创文章 · 获赞 0 · 访问量 47

猜你喜欢

转载自blog.csdn.net/tangsaishi4302/article/details/105272523