1

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.

Thank you all for the help!

Ziki
  • 1,390
  • 1
  • 13
  • 34

2 Answers2

6

You don't need to add g modifier while replacing only the first occurance.

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

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

  1. You should probably look at split() and see how to use it in a greedy way referring to something like this question. Now, use the second half of the split string

  2. Then use replace() to find "string" and change it to "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.

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.

Community
  • 1
  • 1
arjun010
  • 129
  • 1
  • 2
  • 12