1

I am trying to replace all occurrences of http://xyz.yzx.com/abc/def/ by /qwe/ in String in Node js. I am very new to Node js. So, I think I am doing some mistake in syntax. Following is the code with which I am trying.

var newString = originalString.replace("http:\/\/xyz\.yzx\.com\/abc\/def\//g", "/qwe/");

But this is not doing any replace. Can someone suggest what I am doing wrong? I have tried lot of tweaks but somehow I am not able to achieve the replace all occurrences.

Any suggestions you can give would be really appreciated.

7
  • Possible duplicate of How to replace all occurrences of a string in JavaScript? Commented Oct 9, 2017 at 17:44
  • Actually I tried using the same way but somehow I am doing some mistake which I am not able to found out. If you can help me found the mistake in my code, that would be great. Commented Oct 9, 2017 at 17:45
  • 1
    Hmmm, I did not test the code in Node, but a tool tells me, your regex is good enough: regex101.com/r/we8LHA/1 Could you provide a repro case? (A string on which the replacement fails) Commented Oct 9, 2017 at 17:58
  • 1
    @igor theres no regex in the users code ;) Commented Oct 9, 2017 at 18:01
  • 1
    @igor a string is a string :/ Commented Oct 9, 2017 at 18:07

2 Answers 2

3

If a string is passed as replaces first argument it will only replace the first occurence ( which is badly implemented in my opinion). So we either use a small workaround:

var newString = originalString
   .split("http:\/\/xyz\.yzx\.com\/abc\/def")
   .join("/qwe/");

Or we need to remove the string literal and escape every / with a \/ ... :/

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

1 Comment

Now, I see. The regex literal was not used.
1

This works fine, have a look:

originalString.replace(/\http:\/\/xyz\.yzx\.com\/abc\/def\//g, '/qwe/')

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.