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!

2
  • 1
    replace will do this Commented Jul 15, 2015 at 7:21
  • @Tushar at least when given a startIndex based on the position of "here" Commented Jul 15, 2015 at 7:29

2 Answers 2

6

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

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

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

This does not look only after here
I bring here python equivalent, if anyone is looking for: new_str = re.sub(r"\b(HERE.*?)\b\bSTRING", r"\1ANOTHERSTRING", str)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.