如何替换除JavaScript中第一个字符串以外的所有字符串?

如何替换除JavaScript中第一个字符串以外的所有字符串?,javascript,node.js,regex,string,Javascript,Node.js,Regex,String,我有这个字符串: hello world hello world hello world hello 我需要得到以下信息: hello world hello hello hello 如果我使用: str = str.replace('world', ''); 它只删除上述字符串中第一个出现的world 如何替换除第一个事件以外的所有事件?在我的解决方案中,我将用当前时间戳替换第一个事件,然后替换所有事件,最后用world 您还可以使用str.split('world')然后加入 var

我有这个字符串:

hello world hello world hello world hello
我需要得到以下信息:

hello world hello hello hello
如果我使用:

str = str.replace('world', '');
它只删除上述字符串中第一个出现的
world


如何替换除第一个事件以外的所有事件?

在我的解决方案中,我将用当前时间戳替换第一个事件,然后替换所有事件,最后用
world

您还可以使用
str.split('world')
然后加入

var str = 'hello world hello world hello world hello';
var strs = str.split('world');
str = strs[0] + 'world' + strs.slice(1).join('');
console.log(str);
var str='hello world hello world hello world hello';
const d=Date.now()
str=str.replace('world',d.)。replace(/world/gi',)。replace(d,'world');

console.log(str)我会这样做:

  • 获取子字符串,直到并包括第一次出现
  • 将第一次出现后的子字符串附加到该子字符串,并删除所有其他出现项:
  • 函数replaceExceptFirst(str,search){
    让index=str.indexOf(搜索);
    返回str.substring(0,索引+搜索.length)+
    str.substring(index+search.length)。替换(/world/g“”)
    }
    
    log(replaceExceptFirst('hello world hello world hello','world'))
    您可以将一个函数传递给,您可以在其中指定忽略替换第一次出现的内容。另外,将replace的第一个参数设为regex以匹配所有出现的情况

    演示

    let str='hello world hello world hello world hello',
    i=0;
    str=str.replace(/world/g,m=>!i++?m:“”);
    console.log(str)
    
    var str='hello world hello world hello world hello';
    var计数=0;
    var result=str.replace(/world/gi,函数(x){
    如果(计数=0){
    计数++;
    返回x;
    }否则{
    返回“”;
    }
    });
    
    控制台日志(结果)为了提供@Kristianmitk极好答案的另一种选择,我们可以使用一个积极的lookback,这在&Chrome>=62中得到了支持

    const string='hello world hello world hello world hello';
    console.log(
    
    string.replace(/(?@Legman,这不是一个精确的副本。OP并不是询问所有实例。如果时间戳本身是该句子中的一个单词,会发生什么情况?这也是一个非常巧妙的答案!对于节点脚本,问题比浏览器脚本更好。您不需要像问题中那样在简单的情况下使用正则表达式,您可以将字符串与
    replaceAll
    str.replaceAll('world',m=>!i++?m:);