Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove forward and backward slashes from string in javascript

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?

like image 692
CJAY Avatar asked Dec 02 '25 05:12

CJAY


1 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: \/.

like image 107
eisbehr Avatar answered Dec 03 '25 18:12

eisbehr