Remove all Backslashes from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 12, 2021

banner

Check out my new book

Remove all Backslashes from a String #

To remove all backslashes from a string:

  1. Call the replaceAll method, passing it a string containing 2 backslashes as the first parameter and an empty string as the second - str.replaceAll('\\', '').
  2. The replaceAll method returns a new string with all of the matches replaced.
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
Because we want to remove all backslashes, we just replace them with an empty string.

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

The replaceAll method is not supported by Internet Explorer versions 6-11. If you need to support the browser, use the replace method instead.

To remove all backslashes from a string:

  1. Call the replace method, passing it a regular expression matching all backslashes as the first parameter and an empty string as the second.
  2. The replace method will return a new string, which contains no backslashes.
index.js
// Supported in IE 6-11 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 use the g (global) flag because we want to match all occurrences of a backslash and not just the first occurrence.

The replace method does not change the original string, it returns a new string with one or more matches replaced.

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.