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?
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?
Share Improve this question edited Aug 30, 2018 at 15:51 Nimeshka Srimal 8,9305 gold badges45 silver badges60 bronze badges asked Aug 30, 2018 at 11:54 CeejayCeejay 7,26719 gold badges65 silver badges109 bronze badges 04 Answers
Reset to default 16You 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,'');