Table of Contents
Learn about how to remove backslash from String in Java.
backslash() is used as escape character in Java. For example it can be used to:
- Create special characters such as new line character
\n
, tab\t
- Write unicode characters like
\u%04x
.
Ways to Remove Backslash from String in Java
1. Using replace() Method
Use String’s replace()
method to remove backslash from String in Java.
String’s replace()
method returns a string replacing all the CharSequence to CharSequence.
Syntax of replace()
method:
1 2 3 |
public String replace(CharSequence target, CharSequence replacement) |
1 2 3 4 5 |
String pathStr = "C:\\tempFolder\\temp.txt"; pathStr = pathStr.replace("\\",""); System.out.println("String after removing backslash: "+pathStr); |
Output:
As you can see, replace() method replaceed each space with underscore.
2. Using replaceAll()
method
Use replaceAll()
method to remove backslash from String in Java. It is identical to replace()
method, but it takes regex as argument. Since the first argument is regex, you need double escape the backslash. You can go through difference between replace and replaceAll over here.
Here is syntax of replaceAll method:
1 2 3 |
public String replaceAll(String regex, String replacement) |
1 2 3 4 5 |
String pathStr = "C:\\tempFolder\\temp.txt"; pathStr = pathStr.replaceAll("\\\\",""); System.out.println("String after removing backslash: "+pathStr); |
Output:
Further reading:
That’s all about how to remove backslash from String in Java.