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:

public String replace(CharSequence target, CharSequence replacement)  
 String pathStr = "C:\\tempFolder\\temp.txt";
 pathStr = pathStr.replace("\\","");
 System.out.println("String after removing backslash: "+pathStr);

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:

public String replaceAll(String regex, String replacement)  
String pathStr = "C:\\tempFolder\\temp.txt";
pathStr = pathStr.replaceAll("\\\\","");
System.out.println("String after removing backslash: "+pathStr);

Output:

String after removing backslash: C:tempFoldertemp.txt

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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.