【问题标题】:How to replace all instances of a substring but only whole worlds in JS?如何替换子字符串的所有实例,但只替换 JS 中的整个世界?
【发布时间】:2014-02-17 19:41:06
【问题描述】:

例如这个函数

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")

将从这里返回

我的猫头上有顶帽子。

到这里

我的骗子头疼。

但我想回来

我的猫头上戴着一顶帽子。

【问题讨论】:

  • 为什么不手动替换???
  • 这只是一个例子,我想要类比

标签: javascript regex mathcontext


【解决方案1】:

使用单词边界正则表达式定义你的函数:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多