例如这个函数
function replaceAll(str,x,y){
return str.split(x).join(y);
}
var x="My cat have a hat a its head.";
replaceAll(x,"at","on")
将从这里返回
My cat have a hat at its head.
到此
My con have a hon on its head.
但我想返回
My cat have a hat on its head.
最佳答案
使用单词边界正则表达式定义您的函数:
function replaceAll(str,x,y){
return str.split(new RegExp("\\b"+x+"\\b")).join(y);
}
然后:
repl = replaceAll(x,"at","on")
//=> My cat have a hat on its head.
关于javascript - 如何在 JS 中替换子字符串的所有实例但仅替换整个世界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21837896/