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;
}
Answer from KooiInc on Stack OverflowThis 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;
}
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]);
regex - Replace double backslash with single backslash in JavaScript - Stack Overflow
replace - Javascript replacing double backslashed with single backslash - Stack Overflow
regex - Replace with a single backslash in javascript? - Stack Overflow
Can't replace backslash in a string with regex
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.
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
alert(replaceableString);
This will alert you c:asdlkjklsdfjkl because '\' is an escape character which will not be considered.
To have a backslash in your string , you should do something like this..
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
alert(replaceableString);
This will alert you c:\asd\flkj\klsd\ffjkl
JS Fiddle
Learn about Escape sequences here
If you want your string to have '\' by default , you should escape it .. Use escape() function
var replaceableString = escape("c:\asd\flkj\klsd\ffjkl");
alert(replaceableString);
JS Fiddle
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
\isU+5cin 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
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.
You should escape the slash twice:
"tel:\\99999999999".replace('\\\\', '\\');
You can simply use tel.replace(/\\\\/g, "\\").
Demo:
var tel ="\\99999999999";
console.log(tel.replace(/\\\\/g, "\\"));
You need to escape the \ character with another \, because it's an escape character in JavaScript, you can check JavaScript backslash (\) in variables is causing an error for further reading.
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.
How to write it?
You said it yourself:
to display one backslash, I need to write two.
So, if you have two in the string to start with, then you need to replace two (type four) with one (type two).
var filter = "This string has a double slash in it: \\\\";
console.log(`The original string: ${filter}`);
filter = filter.replace("\\\\", "\\");
console.log(`The filtered string: ${filter}`);
Quentin answered your question, but another way to think about it is that two backslashes written into a sting will resolve to a single backslash as soon as you do anything with it.
For example:
Console.Log("\");
//Returns Error
Console.Log("\\");
//Returns: \
var i = "this is a backslash \\"
//i now contains only one backslash
Console.Log(i);
//Returns: this is a backslash \
Edit:
Since you clarified that it's after this in the querying that it gets messed up, you could try making sure you've assigned it to a variable and then passed it to the query.
i = "A string containing backslashes \\"
sql.Query(i);
Edit 2:
Oh, I just got it, you're trying to escape colons ':' which is already handled in JS. So if the query isn't parsing your escape characters than just \: should be perfectly valid.
Andrew Cooper's answer is correct in terms of why that third statement is going wrong. But you're also overwriting newbigbend each time, so you won't see the result of the first two replacements at all.
If you're trying to replace all slashes, backslashes, and asterisks with nothing, do this:
newbigbend = bb_val.replace(/[/\\*]/g, "");
Note you don't need the i flag, none of those characters is case sensitive anyway. (And note that within the [], you don't need to escape / or *, because they don't have special meaning there.) Live example.
But if you want it as three individual statements for whatever reason, then use newbigbend in the second two (and add the backslash Andrew flagged up):
newbigbend = bb_val.replace(/\//gi,"");
newbigbend = newbigbend.replace(/\\/gi,"");
newbigbend = newbigbend.replace(/\*/gi,"");
You also need to escape the *
newbigbend = bb_val.replace(/\*/gi,"");
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));
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(/\\/, "\\\\");