1

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 \\, I need to see a result as follows:

C:\\Users\\Test\\FileName

3
  • 3
    mystring.replace(/\\/g,"\\\\") <- "\\\\" = \\
    – qxz
    May 4, 2017 at 5:41
  • Have you tried logging mystring before replacing? You aren't escaping those backslashes in your sample
    – qxz
    May 4, 2017 at 5:43
  • @TimBiegeleisen You mean four backslashes in the regex? Not with the regex literal syntax (/regex/flags)
    – qxz
    May 4, 2017 at 5:45

2 Answers 2

4

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, '\\\\'));

0
1

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, '\\"');

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.