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.

hatellla
  • 4,130
  • 7
  • 38
  • 78

2 Answers2

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 \/ ... :/

Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
1

This works fine, have a look:

originalString.replace(/\http:\/\/xyz\.yzx\.com\/abc\/def\//g, '/qwe/')
kgangadhar
  • 4,369
  • 4
  • 30
  • 50