How to remove forward and backward slashes from string in javascript

Viewed 16633

I want to remove all the forward and backward slash characters from the string using the Javascript.

Here is what I have tried:

var str = "//hcandna\\"
str.replace(/\\/g,'');

I also tried using str.replace(/\\///g,''), but I am not able to do it.

How can I do it?

4 Answers

You can just replace \/ or (|) \\ to remove all occurrences:

var str = "//hcandna\\"
console.log( str.replace(/\\|\//g,'') );

Little side note about escaping in your RegEx:

A slash \ in front of a reserved character, is to escape it from it's function and just represent it as a char. That's why your approach \\// did not make sense. You escapes \ with \, so it becomes \\. But if you want to escape /, you need to do it like this too: \/.

You want something more like this:

var str = "//hcandna\\"
str=str.replace(/[\/\\]/g,'');
console.log(str);

This will search for the set of characters containing a forward or backward slash and replace them globally. What you had requires a backslash followed by a forward slash.

Here's the output from Node:

  str.replace(/[\/\\]/g,'')
  'hcandna'

You need to add the result to a new string like:

var newstr = str.replace(/(\\|\/)+/ig, '');

You can use this code snippet

str.replace(/(\\|\/)/g,'');
Related