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 OverflowTry:
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
javascript - How can I replace a backslash with a double backslash using RegExp? - Stack Overflow
Can't replace backslash in a string with regex
How to replace single backslash with double backslash in Javascript - Stack Overflow
regex - Replace double backslash with single backslash in JavaScript - Stack Overflow
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.
You should use a escape function provided by some kind of database library, rolling your own will only cause trouble.
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.
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.
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(/\\/, "\\\\");
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;
}
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]);
var myVar = '\"Things You Should Know\"';
document.write(myVar.replace(/\"/g, '|'));
The \ escapes the next character so your string only reads "Things You Should Know"
Your string doesn't have the sequence backslash double-quote in it. The backslash is an escape character so \" means " (this is useful in strings that are delimited by double quote characters).
If you did have that sequence in your string (by escaping the backslash characters):
var myVar = '\\"Things You Should Know\\"';
… then you could do it with:
var modifiedString = myVar.replace(/\\"/g, "|");