Replace every back slash in a JavaScript string with a different character

79 views Asked by At

How can I replace every \ character in a JavaScript string with a different character without using template literals?

An example of myString:

let myString = "This\ \is \\ my \\\\\String";

I have tried using the line: let result = myString.replace(/\\/g, "-"); However, this replaces every 2 back slashes with a dash

I have tried using the line: let result = myString.replace(/\/g, "-"); However, this produces an error

I have tried using the String.raw() function. However, this only works on Template Literal Strings. I am not able to use template literals

1

There are 1 answers

4
KooiInc On

Single backslashes (\) in a string literal are interpreted as character escapes. Every \ that's not a character escape should be escaped on itself.

// in myString, \ , \i and \S are interpreted as escape sequences
const myString = "This\ \is \\ my \\\\\String";;
// so this won't work as you may expect
console.log(myString.replace(/\\/g, `-`));

// every '\' should be escaped on itself in a string literal
const myStringOk = "This\\ \\is \\\\ my \\\\String";;
// now it works
console.log(myStringOk.replace(/\\/g, `-`));