Javascript regex replace with escaped backslash - javascript

I have a question about the replace backlash pattern with JavaScript replace method.
var display_user = "mycompany\bobandalice";
display_user = display_user.replace(/\\/g,"\\\\");
document.write(display_user);
I am hoping to substitute the backslash in the display_user with two back slashes so the document.write displays "mycompany\bobandalice" on the display.
Instead it displays "mycompanyobandalice".
What am I doing wrong ? (Thanks for your help)

The display_user variable does not have the backslash literal at all, so you have nothing to replace.
When "mycompany\bobandalice" string is evaluated the \b sequence is interpreted as a backspace.
So the replace does not replace anything because it's too late - the backslash is not and honestly - was not there ever.

The display_user string doesn't actually have a backslash character. Try escaping the backslash. Something like this:
var display_user = "mycompany\\bobandalice";
// ^ notice the escaped backslash
display_user = display_user.replace(/\\/g, '\');

Related

Backslashes are getting removed from string

Javascript removes back slashes from string.
var a='https:\\abc\qwe.com';
console.log(a);
var b=encodeURI(a);
console.log(b);
var c='https:\\\abc\\qwe.com';
console.log(c);
var d='https:\\\\abc\\qwe.com';
console.log(d);
Is there any way to get Javascript to not remove the backslashes in the console.log input strings?
In JavaScript (and other languages) the backslash \ is used as an escape character, f.e. to be able to get a double quote in your string: "\"". (Read more here under Escape notation)
The side effect is that, if you want a backslash in your string, you need a double backslash: "\\" results in \.
This said, URL's use slashes instead of backslashes: "https://abc/qwe"
If you're looking for URL encoding, use the encodeURI or encodeURIComponent function.
You are using backslashes, not slashes(/). They are used to escape special symbols (and the backslash itself). You do not need them to write URLs, actually.

Backslash bug in JavaScript

I have a string that involves tricky \\ characters.
Below is the initial code, and what I am literally trying to achieve but it is not working. I have to replace the \" characters but I think that is where the bug is.
var current = csvArray[0][i].Replace("\"", "");
I have tried the variation below but it is still not working.
var current = csvArray[0][i].Replace('\"', '');
It is currently throwing an Uncaught TypeError: csvArray[0][i].Replace is not a function
Is there a way for Javascript to take my string ("\"") literally like in C#? Kindly help me investigate. Thanks!
If the sequence you want to match is a single backslash character followed by a quotation mark, then you need to escape the backslash itself because backslashes have special meaning in string literals. You then need to separately escape the quotation mark with its own backslash:
.replace("\\\"", "")
I believe that would also be true in C#.
Or you can simplify it by using single quotes around the string so that only the backslash needs to be escaped:
.replace('\\"', '')
If the first argument to .replace() is a string, however, it will only replace the first occurrence. To do a global replace you have to use a regular expression with the g flag, noting that backslashes need to be escaped in regular expressions too:
.replace(/\\"/g, '')
I'm not going to setup a demo array to exactly match your code, but here's a simple demo where you can see that a lone backslash or quote in the input string are not replaced, but all backslash-quote combinations are replaced:
var input = 'Some\\ test" \\" text \\" for demo \\"'
var output = input.replace(/\\"/g, '')
console.log(input)
console.log(output)

Backslash escape in indexOf

Why does n give 0 in the following instance :
var str = '\\nvga032.bmwgroup.net\QXE7868\Daten\IE\3_bookmarks.zzz'
var n = str.indexOf("\\");
alert(n) //0
Surely the escape character for a backslash is
'\\'
Am I missing something? I am looking for a single backslash at the last position. I tried lastIndexOf as well, and that also gives zero. Are the two '.'s messing things up?
indexOf matches on the string not the JavaScript source code used to create it.
A \ character starts an escape sequence.
\\ is the escape sequence for "A backslash".
The string assigned to str starts with \\ which puts a backslash in position 0 in the data.
The string passed to indexOf consists entirely of \\ which matches the first backslash in the data.
If you wanted to describe an escape sequence in a string you would use \\\\ (i.e. the escape sequence for a backslash followed by another escape sequence for a backslash resulting in data consisting of two backslashes).
"\\" will be parsed down to a single blackslash. And then indexOf will look for that single backslash, which happens to be at the start of the string (n=0).
If you want to search for TWO backslashes, you'll have to indexOf("\\\\") (FOUR backslashes, which will be parsed down to two literal backslashes).
Your "str" variable most probably doesn't contain what you expected. Write instead:
var str = '\\\\nvga032.bmwgroup.net\\QXE7868\\Daten\\IE\\3_bookmarks.zzz'
var n = str.lastIndexOf("\\");

How to remove backslash from a string in JavaScript

I have a string like this:
<tr><td><span class=\'label label-info\'>Dialed</span></td><td>9804292145453</td><td>A Jana</td><td>0sec</td><td>6:18PM, Mar 24, 2014</td></tr>
I want to remove the backslash & want result like this :
<tr><td><span class='label label-info'>Dialed</span></td><td>9804292145453</td><td>A Jana</td><td>0sec</td><td>6:18PM, Mar 24, 2014</td></tr>
Please help.
You've said what you quoted above is a string, but it's unclear whether you mean this (shortened a bit):
var str = "<tr><td><span class=\'label label-info\'>Dialed...";
...where what you've quoted is what you literally have within quotes, or this (note the backslashes):
var str = "<tr><td><span class=\\'label label-info\\'>Dialed...";
...where what you've quoted is the actual content of the string, not part of a string literal.
The first one above doesn't have any backslashes in it, it has escaped ' characters. The second one has backslashes in it.
To remove the backslahes from the second one:
str = str.replace(/\\/g, "");
When you give a regular expression with the g flag to replace, it applies globally throughout the string. Backslashes have special meaning in regular expressions, and so I've had to escape the backslash (with another backslash, it's the escape character for regular expressions as well as strings). So in the above, I'm saying to replace all backslashes with an empty string.
you can use RegExp to find backslash in JS string like this:
string.eplace(/\\\//g, "/");
demo

How can I use backslashes (\) in a string?

I tried many ways to get a single backslash from an executed (I don't mean an input from html).
I can get special characters as tab, new line and many others then escape them to \\t or \\n or \\(someother character) but I cannot get a single backslash when a non-special character is next to it.
I don't want something like:
str = "\apple"; // I want this, to return:
console.log(str); // \apple
and if I try to get character at 0 then I get a instead of \.
(See ES2015 update at the end of the answer.)
You've tagged your question both string and regex.
In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \\.
The following string starts with one backslash, the first one you see in the literal is an escape character starting an escape sequence. The \\ escape sequence tells the parser to put a single backslash in the string:
var str = "\\I have one backslash";
The following regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character starting an escape sequence. The \\ escape sequence tells the parser to put a single backslash character in the regular expression pattern:
var rex = /\\/;
If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:
// Matches *one* backslash
var rex = new RegExp("\\\\");
That's because first, you're writing a string literal, but you want to actually put backslashes in the resulting string, so you do that with \\ for each one backslash you want. But your regex also requires two \\ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)
ES2015 and ES2018 update
Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:
// Yes, this unlikely-looking syntax is actually valid ES2015
let str = String.raw`\apple`;
str ends up having the characters \, a, p, p, l, and e in it. Just be careful there are no ${ in your template literal, since ${ starts a substitution in a template literal. E.g.:
let foo = "bar";
let str = String.raw`\apple${foo}`;
...ends up being \applebar.
Try String.raw method:
str = String.raw`\apple` // "\apple"
Reference here: String.raw()
\ is an escape character, when followed by a non-special character it doesn't become a literal \. Instead, you have to double it \\.
console.log("\apple"); //-> "apple"
console.log("\\apple"); //-> "\apple"
There is no way to get the original, raw string definition or create a literal string without escape characters.
please try the below one it works for me and I'm getting the output with backslash
String sss="dfsdf\\dfds";
System.out.println(sss);

Categories