Replace Backslash with Forward Slash in Java

1. Introduction

In this post, we will learn about how to replace backslash with forward slash in java.

backslash() is used as escape character in Java. For example:
It can be used to:

  • Used in special characters such as new line character \n, tab \t
  • Write unicode characters like \u%04x.

That’s the reason we can’t directly replace backslash to forward slash. We need to escape it while replacing it.

Let’s go through different ways to do it.

2. Using replace() Method

Use String’s replace() method to replace backslash with forward slash in java.

String’s replace() method returns a string replacing all the CharSequence to CharSequence.
Syntax of replace() method:

Here is an example:

Output:

C:/tempDir/temp.txt

As you can see, replace() method replaceed each space with underscore.

3. Using replaceAll() method

Use replaceAll() method to replace backslash with forward slash 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.

Here is syntax of replaceAll method:

Output:

C:/tempDir/temp.txt

That’s all about how to replace backslash with forward slash in java.

Was this post helpful?

Leave a Reply

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