Skip to content Skip to sidebar Skip to footer

How To Replace "\" With "\\" From A String Using Javascript?

I tried mystring.replace(/\\/g,'\\') but that didn't work. Can someone advise me how to do this replacement? Example: String = 'C:\Users\Test\FileName' When I replace \ with \\,

Solution 1:

Inside string \-backslash is used to escape the following character. In the string, "C:\Users\Test\FileName" also backslash is used as escape sequence and actual string is "C:UsersTestFileName"

var str = "C:\Users\Test\FileName";
console.log(str);

To make this correct, the backslashes in the string should already escaped.

var str ="C:\\Users\\Test\\FileName";

var str = "C:\\Users\\Test\\FileName";
console.log(str);

The regex can now be used to double the backslashes

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

var str = "C:\\Users\\Test\\FileName";
console.log(str);
console.log(str.replace(/\\/g, '\\\\'));

Solution 2:

Try this, use raw string,String.raw() method is a tag function of template literals

String.raw`\"`.replace(/\"/g, '\\"');

or,if first one isn't work,try this :) hope this will be helped to you

String.raw\".replace(/\\"/g, '\\"');

Post a Comment for "How To Replace "\" With "\\" From A String Using Javascript?"