Remove all Backslashes from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Sep 4, 2022

banner

Photo from Unsplash

Remove all Backslashes from a String #

Use the String.replaceAll() method to remove all backslashes from a string, e.g. str.replaceAll('\\', ''). The replaceAll() method will remove all backslashes from the string by replacing them with empty strings.

index.js
const str = '1\\2\\3'; const replaced = str.replaceAll('\\', ''); console.log(replaced); // 👉️ '123'

The parameters we passed to the String.replaceAll method are:

  1. a substring we want to match in the string. Notice that we need to escape the backslash with another backslash.
  2. the replacement string, in our case an empty string
We want to remove all backslashes, so we just replace them with an empty string.

As the name suggests, the str.replaceAll() method replaces all occurrences of the string with the substring and not just the first occurrence.

Note that the replaceAll method doesn't change the contents of the original string, it returns a new string with the matches replaced. Strings are immutable in JavaScript.

Alternatively, you can use the str.replace() method.

Remove all Backslashes from a String #

Use the String.replace() method to remove all backslashes from a string, e.g. const replaced = str.replace(/\\/g, '');. The String.replace() method will remove all backslashes from the string by replacing them with empty strings.

index.js
const str = '1\\2\\3'; const replaced = str.replace(/\\/g, ''); console.log(replaced); // 👉️ 123

The String.replace method takes the following parameters:

  1. a regular expression we want to match in the string. Again, we have to escape the backslash with another backslash
  2. the replacement string - in our case an empty string

We used the g (global) flag because we want to match all occurrences of a backslash and not just the first occurrence.

The replace method doesn't change the original string, it returns a new string with one or more matches replaced.

Which approach you pick is a matter of personal preference, I'd go with the String.replaceAll() method to be able to use a string instead of a regular expression.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.