Try:

   var parts = replaceableString.split('\\');
   var output = parts.join('\\\\');

Personally, as I am not so expert in reg exps, I tend to avoid them when dealing with non-alphanumeric characters, both due to readability and to avoid weird mistake.

Answer from LittleSweetSeas on Stack Overflow
Discussions

javascript - How can I replace a backslash with a double backslash using RegExp? - Stack Overflow
I need to modify the value using javascript, to make it ready to be put as part of a SQL insert query. Currently I have the following code to handle the single quote ' character. value = value. More on stackoverflow.com
🌐 stackoverflow.com
December 31, 2011
Can't replace backslash in a string with regex
const name = 'AC\\DC'; should work. More on reddit.com
🌐 r/learnjavascript
11
6
May 2, 2023
How to replace single backslash with double backslash in Javascript - Stack Overflow
I have seen a lot of duplicates but none of them works I spend a day to get this thing up. Gone through all duplicates I need to replace a single backslash with a double backslash. I am able to re... More on stackoverflow.com
🌐 stackoverflow.com
regex - Replace double backslash with single backslash in JavaScript - Stack Overflow
I am writing a function that will remove a \\ and replace it with a \. I notice that the code also does not work for backslashes that aren't powers of two (other than two, of course). function x(i... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Directory Opus
resource.dopus.com › off-topic
Find and Replace Backslash in a JavaScript String - Off-Topic - Directory Opus Resource Centre
December 9, 2023 - It is related to this post: Rename command, {alias} code and Double backslashes Objective In a JavaScript string variable I have reason to want to replace all instances of backslash \ With TWO instances of (the same) backslash: \ How do I do this in JavaScript in DO?
Top answer
1 of 2
25

Now I noticed that stand-alone backslashes are causing errors.

Backslashes in the string you're operating on won't have any effect on replacing ' characters whatsoever. If your goal is to replace backslash characters, use this:

value = value.replace(/\\/g, "whatever");

...which will replace all backslashes in the string with "whatever". Note that I've had to write two backslashes rather than just one. That's because in a regular expression literal, the backslash is used to introduce various special characters and character classes, and is also used as an escape — two backslashes together in a regular expression literal (as in a string) represent a single actual backslash in the string.

To change a single backslash into two backslashes, use:

value = value.replace(/\\/g, "\\\\");

Note that, again, to get a literal backslash in the replacement string, we have to escape each of the two — resulting in four in total in the replacement string.

I need to modify the value using javascript, to make it ready to be put as part of a SQL insert query.

You don't want to do this by hand. Any technology that allows you to make database queries and such (JDBC, ODBC, etc.) will provide some form of prepared or parameterized statement (link), which deals with these sorts of escaping issues for you. Doing it yourself is virtually guaranteed to leave security holes in your software which could be exploited. You want to use the work of a team that's had to think this through, and which updates the resulting code periodically as issues come to light, rather than flying alone. Further, if your JavaScript is running on the client (as most is, but by no means all — I use JavaScript server-side all the time), then nothing you do to escape the string can make it safe, because client requests to the server can be spoofed, completely bypassing your client-side code.

2 of 2
3

You should use a escape function provided by some kind of database library, rolling your own will only cause trouble.

🌐
Reddit
reddit.com › r/learnjavascript › can't replace backslash in a string with regex
r/learnjavascript on Reddit: Can't replace backslash in a string with regex
May 2, 2023 -

I need to replace all backslashes in a string with another symbol. I use regex for that, but it just doesn't work

const name = 'AC\DC'; 
const replaced = icon.replace(/\\/g, "-");

console.log(name);
console.log(replaced);

// ACDC
// ACDC

For example in this string the backslash is not replaced and not even shown when I log the origial string in a console.

🌐
Google Groups
groups.google.com › g › mathjax-users › c › U26soxRWoc4
Changing single backslashes to double ones
The doubling of backslashes isn't something that you will be able to do from within the javascript itself; they have to be there BEFORE javascript parses the string literal. If you really want to double the backslashes that are in a string stored in a variable, then you can use ... which does a search and replace on the contents of cs, searching of a single slash (which we had to double in order to get an actual slash in the pattern) and replaces it by a double slash (which we had to represent as two pairs of slashes, each becoming a single slash in the replacement string).
🌐
Stack Overflow
stackoverflow.com › questions › 63591707 › how-to-replace-single-backslash-with-double-backslash-in-javascript
How to replace single backslash with double backslash in Javascript - Stack Overflow
var str = "AAA\\BBB\\CCC\\DDD\\EEE"; ... are very revealing. Single backslash \ is escape character. To obtain single backslash we must use double backslashes....
Top answer
1 of 2
3

When using regex,

  • a literal reverse solidus (a.k.a. backslash,( a.k.a. \)) must be escaped with a \ .

  • So when you input \\, that's literally \.

  • If you want to input 2 \ each one must be escaped. That means \\\\ is literally a string of 2 \.

The following demo uses ES6 Template Literals:

  • It's a new syntax for String that uses the backtick ` (top left corner key) instead of quotes " or '.

  • It can interpolate variables by prefixing with ${ and suffixing with }.

    var x = 2; `this template literal will display x as ${x}.`
    // this template literal will display x as 2.
    
  • The \ is U+5c in unicode. Using escaped unicode in Template Literal, it would be prefixed with \u{ and suffixed with }

    `A template literal with an escaped unicode backslash is \u{5c}`
    // A template literal with an escaped unicode backslash is \.
    

Demo

function XtoY(str, x, y) {
  var rgx = `/${x}/g`;
  var result = str.replace(rgx, `${y}`);
  return result;
}

const uni = `\u{5c}`;
const string = `\\a\\a\\b`;
const from = `${uni}${uni}`
const to = `${uni}`;

let z = XtoY(string, from, to);

console.log(z);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 2
0

When we pass in "["\\\\\\"\\"a\\""]" into with console.log(), the string that the function actually sees looks like "["\\\"\"a\""]" because the input string is being escaped before being passed to the function. The replace regex looks for double backslashes, so given the input, it will only match the first two backslashes of that group of three, replacing it with one, and leaving the rest as is... which is why it will return "["\\"\"a\""]".

If you call the function, getting the input string from an input field, for instance, your function works as desired.

If you WANT to achieve your desired result using explicit string literals, you can use /\\/g as the replace regex (effectively just not doing the replace at all), but it will not work both ways unless, as far as I know, you provide the function a way of knowing where the string came from (perhaps with an optional parameter) and manually handling the possibilities.

For example:

function x(input, caller) {
  return input.replace(caller === 'console' ? /\\/g : /\\\\/g, "\\");
}

console.log(x('["\\\\\\\"\\"a\\""]', "console"));

$("button").click(function() {
  console.log(x($("input").val()));
});

That checks if the call to the x function was passed a 2nd parameter with the value of "console" and changes the regex for the replace function accordingly.

Find elsewhere
🌐
Experts Exchange
experts-exchange.com › questions › 20390114 › Replacing-a-Backslash-with-a-double-backslash.html
Solved: Replacing a Backslash with a double backslash | Experts Exchange
March 10, 2008 - Try <script type=text/javascript> var dir0= new String("c:\\a\\b\\c") alert(dir0) alert(dir0.replace(/\\/g," \\\\")) </script> You need to put the \\ into the string when it is created. So on the server side. ... Check out this function... It returns a string with \\ instead of \ <script> function changeit(dir0){ temp = ""; for(x=0;x<dir0.length;x++)
🌐
Pentaho
forums.pentaho.com › threads › 53752-Replacingi-backslashes-(-)-to-double-backslashes-(-)-in-mod-javascript-value-object
Replacingi backslashes (\) to double backslashes (\\) in mod. javascript value object
May 3, 2007 - - then in your javascript step : var arg3 = arg0 + "\\" + arg1 + "\\" + arg2; You have to use two step, but it works... Regards Gambi ... Hi again I found that java script value modified step uses java replaceAll function to replace strings, and also found that there are some issues when replacing backslashes with that function, because first parameter for replaceAll function is regex.
Top answer
1 of 3
36

This should do it: "C:\\backup\\".replace(/\\\\/g, '\\')

In the regular expression, a single \ must be escaped to \\, and in the replacement \ also.

[edit 2021] Maybe it's better to use template literals.

console.log(`original solution ${"C:\\backup\\".replace(/\\\\/g, '\\')}`)

// a template literal will automagically replace \\ with \
console.log(`template string without further ado ${`C:\\backup\\`}`);

// but if they are escaped themselves
console.log(`Double escaped ${`C:\\\\backup\\\\`.replace(/\\{2,}/g, '\\')}`);

// multiple escaped
console.log(`multiple escaped ${`C:\\\\\\\\backup\\\\`
  .replace(/\\{2,}/g, '\\')}`);

// don't want to replace the last \\
console.log(`not the last ${`C:\\\\\\backup\\\\`
  .replace(/\\{2,}([^\\{2,}$])/g, (a ,b) => a.slice(0,1) + b)}` );

// don't want to replace the first \\
console.log(`not the first ${`C:\\\\backup\\`.replace(/\\[^\\]$/g, '\\')}`);

// a generic tagged template to replace all multiple \\ OR //
const toSingleSlashes = (strs, ...args) => 
  strs.reduce( (a, v, i ) => 
    a.concat(args[i-1] || ``).concat(v, ``), `` )
      .replace( /(\\|\/){2,}/g, (a, b) => b );

console.log(`generic tagged template 1 ${
  toSingleSlashes`C:\\backup\\`}`);

console.log(`generic tagged template 2 ${
  toSingleSlashes`C:\\\\\\\\backup\\\\\\\\\\`}`);
  
console.log(`generic tagged template 3 ${
  toSingleSlashes`C:\\\\\\\\backup\\`}`);
  
console.log(`generic tagged template 4 ${
  toSingleSlashes`C:////////backup////`}`);

console.log(`reply to comment @chitgoks => 
"test\\\\hehehe" is by default "test\\hehehe"
so, no replacement necessary here ...`);
.as-console-wrapper {
    max-height: 100% !important;
}

2 of 3
3

Best is to use regex to replace all occurrences:

C:\\backup\\".replace(/\/\//g, "/")[0]

this returns: C:\backup\

OR

use split()

"C:\\backup\\".split();

both produces your desired result

C:\backup\

console.log("using \"C:\\backup\\\".replace(/\/\//g, \"/\")")
console.log("C:\\backup\\".replace(/\/\//g, "/"));

console.log("Using \"C:\\backup\\\".split()");
console.log("C:\\backup\\".split()[0]);

🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-replace-all-backslashes-in-string
Replace or Remove all Backslashes in a String in JavaScript | bobbyhadz
March 1, 2024 - By adding a second backslash, we treat the backslash character as a literal backslash \ instead of an escape character. If you have to do this often, define a reusable function. ... Copied!function replaceAllBackslashes(string, replacement) ...
🌐
RegExr
regexr.com › 3f8od
double-backslash
Supports JavaScript & PHP/PCRE RegEx. Results update in real-time as you type. Roll over a match or expression for details. Validate patterns with suites of Tests.
🌐
Stack Overflow
stackoverflow.com › questions › 33396522 › converting-double-backslash-into-backslash-used-for-escaping
javascript - Converting double backslash into backslash used for escaping? - Stack Overflow
JavaScript works on a special way in this case. Read this for more details. In your case it should be one of this ... var JSCodeNewLine = "\u000A"; text.replace(/\\n/g, JSCodeNewLine); var JSCodeCarriageReturnNewLine = "\u000D\u000A"; text.replace(/\\n/g, JSCodeCarriageReturnNewLine); ... This is wrong. He wants to convert an actual backslash followed by the letter n into a newline.