15

我有一根绳子:

你好世界你好世界你好世界你好

我需要获得以下信息:

你好世界你好你好你好

如果我使用:

str=str.replace('world','');

它只删除第一次出现的世界在上面的字符串中。

如何替换除第一个以外的所有出现的内容?

2

6个答案6

重置为默认值
20

您可以将函数传递给字符串#替换,其中可以指定忽略替换第一个匹配项。还要使您的第一个参数代替匹配所有事件的正则表达式。

演示

let str='hello world hello world-hello world-hello world-hello world hello',i=0;str=str.replace(/world/g,m=>!i++?m:'');console.log(str);

注释

您可以避免使用全局计数器变量通过使用IIFE公司:

let str='hello world hello world-hello world-hello world-hello world hello';str=str.replace(/world/g,(i=>m=>!i++?m:'')(0));console.log(str);

为了提供@Kristianmitk优秀答案的替代方案,我们可以使用一个积极的后备方案,该方案在节点。Js公司&铬>=62

const string='hello world hello world-hello world-hello world-hello world hello';控制台.log(string.replace(/(?<=world[\s\s]+)world/g,“));//或控制台.log(string.replace(/(?<=(世界)[\s\s]+)\1/g,''));


使用符号.替换著名的符号。

Symbol.replace众所周知的符号指定用于替换字符串中匹配的子字符串。此函数由调用String.prototype.replace()方法。

const string='hello world hello world-hello world-hello world-hello world hello';类ReplaceButFirst{构造函数(word,replace=“”){this.count=0;this.replace=替换;this.pattern=新RegExp(单词,'g');}[符号替换](str){return str.replace(this.pattern,m=>!this.count++?m:this.replace);}}控制台.log(string.replace(new ReplaceButFirst('world')));

1
  • 1
    这也是一个非常巧妙的答案!探测节点脚本比探测浏览器脚本更好。 评论 2018年4月25日0:37
1

var str='hello world hello world-hello world-hello world-hello world hello';var计数=0;var结果=str.replace(/world/gi,函数(x){如果(计数==0){计数++;返回x;}其他{返回“”;	}});console.log(结果);

1

在我的解决方案中,我将第一次出现替换为当前时间戳,然后替换所有出现,最后将时间戳替换为世界

您还可以使用str.split(“世界”)然后加入

var str='hello world hello world-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 world-hello world hello';const d=日期.now()str=str.replace('world',d).replace[(/world/gi,'').replay(d,'world]);console.log(str);

1
  • 2
    如果时间戳本身是句子中的一个单词,会发生什么? 评论 2018年4月24日23:49
1

在没有附加功能或查找的情况下,可以使用诡计.

let str='hello world hello world-hello world-hello world-hello world hello';str=str.replace(/^(.*?world)|world/g,'$1');console.log(str);

请参阅此regex101演示

来自的部分^开始直到第一次出现世界(懒惰的.*?之间)得到捕获通过第一组 |还有剩余的吗世界s通常是匹配的。在这种情况下,“诀窍”是捕获交替左侧需要什么| 但匹配是什么右侧需要。

替换是$1并包含直到第一个世界如果左边成功了。否则,如果右侧匹配第一组将为空-因此世界被删除。


从现在开始lookbehind可用在JS regex中,另一个想法是代替(世界)(?<=\1.+)为空。它检查捕获是否发生在字符串中之前,并且不一定更有效。

0

我会这样做:

  1. 获取子字符串,直到并包含第一个匹配项。
  2. 将子字符串附加到第一个匹配项之后,并删除所有其他匹配项:

函数replaceExceptFirst(str,search){let index=str.indexOf(搜索);返回str.substring(0,index+search.length)+str.substring(index+search.length).replace(/world/g,“”)}console.log(replaceExceptFirst('hello world hello worth hello','world'))

你的答案

单击“发布您的答案”,表示您同意我们的服务条款并确认您已阅读我们的隐私政策.

不是你想要的答案吗?浏览标记的其他问题问你自己的问题.