Remove Backslash from String in Java

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:

Output:

String after removing backslash: C:tempFoldertemp.txt

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:

Output:

String after removing backslash: C:tempFoldertemp.txt

That’s all about how to remove backslash from String in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *