String replace a Backslash

kensen john picture kensen john · Apr 8, 2011 · Viewed 108.5k times · Source

How can I do a string replace of a back slash.

Input Source String:

sSource = "http://www.example.com\/value";

In the above String I want to replace "\/" with a "/";

Expected ouput after replace:

sSource = "http://www.example.com/value";

I get the Source String from a third party, therefore I have control over the format of the String.

This is what I have tried

Trial 1:

sSource.replaceAll("\\", "/");

Exception Unexpected internal error near index 1 \

Trial 2:

 sSource.replaceAll("\\/", "/");

No Exception, but does not do the required replace. Does not do anything.

Trial 3:

 sVideoURL.replace("\\", "/"); 

No Exception, but does not do the required replace. Does not do anything.

Answer

Bozho picture Bozho · Apr 8, 2011
sSource = sSource.replace("\\/", "/");
  • String is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)
  • replaceAll(..) uses regex. You don't need that.