Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and backslashes replace

here is my string:

var str = "This is my \string"; 

This is my code:

var replaced = str.replace("/\\/", "\\\\"); 

I can't get my output to be:

"This is my \\string" 

I have tried every combination I can think of for the regular expression and the replacement value.

Any help is appreciated!

like image 397
Frankie Avatar asked Mar 19 '10 17:03

Frankie


People also ask

How do you remove backslashes from string?

To remove all backslashes from a string:Call the replaceAll method, passing it a string containing 2 backslashes as the first parameter and an empty string as the second - str. replaceAll('\\', '') . The replaceAll method returns a new string with all of the matches replaced.

How do I get rid of backslash in HTML?

Try: string. replace(/\\\//g, "/");

How do you replace a backslash in a string in Java?

replaceAll("\\/", "/");


2 Answers

Got stumped by this for ages and all the answers kept insisting that the source string needs to already have escaped backslashes in it ... which isn't always the case.

Do this ..

var replaced = str.replace(String.fromCharCode(92),String.fromCharCode(92,92)); 
like image 148
thegajman Avatar answered Sep 21 '22 19:09

thegajman


The string doesn't contain a backslash, it contains the \s escape sequence.

var str = "This is my \\string"; 

And if you want a regular expression, you should have a regular expression, not a string.

var replaced = str.replace(/\\/, "\\\\"); 
like image 38
Quentin Avatar answered Sep 21 '22 19:09

Quentin