简体   繁体   English

在另一个字符串之后替换第一次出现的字符串

[英]replace first occurrence of string after another string

Tried to find it in the network without any success.. 试图在网络中找不到它。

Let's say I have the following string: 假设我有以下字符串:

this is a string test with a lot of string words here another string string there string here string. 这是一个字符串测试,其中包含很多字符串单词,另外一个字符串字符串,这里的字符串。

I need to replace the first ' string ' to ' anotherString ' after the first ' here ', so the output will be: 我需要在第一个“ 这里 ”之后将第一个“ 字符串 ”替换为“ 另一个 字符串 ”,因此输出将是:

this is a string test with a lot of string words here another anotherString string there string here string. 这是一个字符串测试,其中有很多字符串单词,另一个anotherString字符串,这里的字符串。

Thank you all for the help! 谢谢大家的帮助!

You don't need to add g modifier while replacing only the first occurance. 仅替换第一个匹配项时,无需添加g修饰符。

str.replace(/\b(here\b.*?)\bstring\b/, "$1anotherString");

DEMO DEMO

If you are looking for something which takes in a sentence and replaces the first occurrence of "string" after "here" (using the example in your case), 如果您要查找一个包含句子的内容,并替换“ here”之后的第一个出现的“ string”(以您的情况为例),

  1. You should probably look at split() and see how to use it in a greedy way referring to something like this question . 您可能应该看一下split() ,看看如何以贪婪的方式使用它来引用类似此问题的东西。 Now, use the second half of the split string 现在,使用分割字符串的后半部分

  2. Then use replace() to find "string" and change it to "anotherString". 然后使用replace()查找“字符串”,并将其更改为“ anotherString”。 By default this function is greedy so only your first occurrence will be replaced. 默认情况下,此功能为贪婪功能,因此只有您的第一次出现会被替换。

  3. Concatenate the part before "here" in the original string, "here" and the new string for the second half of the original string and that will give you what you are looking for. 将原始字符串中“ here”之前的部分,“ here”和新字符串(原始字符串的后半部分)连接起来,这将为您提供所需的内容。

Working fiddle here . 在这里工作。

inpStr = "this is a string test with a lot of string words here another string string there string here string."

firstHalf = inpStr.split(/here(.+)?/)[0]
secondHalf = inpStr.split(/here(.+)?/)[1]
secondHalf = secondHalf.replace("string","anotherString")

resStr = firstHalf+"here"+secondHalf
console.log(resStr)

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM