Javascript: unable to escape backslash in IE - javascript

Very simply, I want to assign a variable the value of a single backslash character. The problem is:
var myVar = '\'; // breaks because the backslash escapes the closing quote
var myVar = '\\'; // now myVar has two backslashes
Everything I can find says that you escape a backslash with a backslash, which is what I have always known to be generally true. However, when I run this in IE I get two backslashes instead of one.
Here's a screenshot of the IE debugger attempting to replace a # with a . This problem occurs anywhere I try to escape a backslash with a string literal - the string.replace() function yields the same error.
[Edit]
Thanks for the comments. In the short term I'll probably use octal or hexadecimal ascii as several people have recommended. But what I would really like is to understand why I can't just escape the backslash.
Here's a better screenshot without the string.replace function. Same result.
[/Edit]

Well if it's bothering you too much, use octal or hexadecimal ascii code ;)

Try using this:
var backslash = String.fromCharCode(92);
For example: http://jsfiddle.net/lbstr/Sjja3/
EDIT:
I don't see any need for the replace function. Why don't you just do this? It works fine for me in IE.
if( dirPath === "#" ) dirPath = '\\';

Turns out #Prusse had it right: it wasn't a problem escaping the backslash, the problem was that the IE debugger renders '\' as '\\'. In my case I had an underlying problem that behaved the same way a mangled string would have so it took a while to track this down.
Solution:
Did you try to alert it? (with alert(myVar))
-Prusse

It makes sense to me that it shows the \\ instead of \. Look at the line it has quotes.
So if the string "\\nope" is totally different than "\nope". Now if the debugger did not have quotes surrounding the string, I would expect just one slash.

Related

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)

remove illegal characters from file name javascript

I've seen the various posts regarding this topic, but I'm getting a strange result when I do the following:
var dirtyString = '<>I\really|\re\ad?"the/wh\ole*:da|\y?.'
var cleanString = dirtyString.replace(/[\/:*?"<>|.]/g, "");
console.log(cleanString);
It removes all the illegal characters, but the "r" letters are also removed. In the console log I'm getting "Ieallyeadthewholeday" It seems that "\" before "r" erases the "r". "\" isn't erasing other letters it comes before. Am I missing something?
If you would try console.log(dirtyString) you would also see that your "r" are "missing" too.
This is because '\r' is actually an escape sequence for Carriage Return character (code 13). Your replace() does nothing to it. It is still there just isn't displayed. Try playing with String.charAt() and String.charCodeAt() and you will see that the character is still there.
As a side note you are trying to remove "blacklisted" characters and blacklisting is almost never right approach. As you can see in your own case you forgot to blacklist '\r' character (and many others). Much safer is whitelisting. For example you may decide that you accept only latin letters and digits, then remove everything not whitelisted: var cleanString = dirtyString.replace(/[^a-z0-9]/gi, "");.
\r is the Carriage Return character. If you want a backslash followed by an r then you need to escape the backslash: \\r.
\y is not a reserved escape sequence, so JavaScript interprets it as \ followed by y. Other programming languages, like C#, will instead raise a compiler error about an unrecognised escape sequence.
Further confounding things: most regular-expression syntaxes have their own backslash escape sequences that are distinct from the hosting language's, such as the character-classes \W, \d etc. Fortunately they work because \W and \d are not reserved in JavaScript, but in this author's opinion it makes sense to escape the backslashes then just to make things really clear to the reader, or if you're wanting to make your regexes portable between languages.

removing backslash in a string with Javascript/jQuery

When I query twitter feeds, the returned profile url contains backslashs
and looks like:
"http:\/\/a0.twimg.com\/profile_images\/2419298032\/image_normal.jpg"
how to remove the backslashes to make it look like:
"http://a0.twimg.com/profile_images/2419298032/image_normal.jpg"
Thanks a lot!
P.S. seems
x=x.replace(/\/gi, "");
doesn't work...
x = x.replace(/\\/g, '');
You have to use two backslashes to get the \ character. A single backslash is used for control characters such as \r \n etc. Using the double backslash escapes this and gives you what you want.
See also: how can remove backslash in value by jQuery?

Javascript replace unescaped slash

I want to replace an unescaped slash in a string with backslash. But something weird happened:
"\content\hs\gj\home.css".replace(/\\/gi,"/")
which returns "contenthsgjhome.css". I understand that if change it to
"\\content\\hs\\gj\\home.css".replace(/\\/gi,"/")`
Then it will work as expected, but I can't change the string because it's just the output by nodejs path.join("conetnt", "hs", "gj", "home.css").
What I should do?
The reason it is returning "contenthsgjhome.css" is that your string doesn't really have any backslashes in it at all because single backslashes in a string literal will be ignored unless they make sense to escape the following character (e.g., "\\" or "\n"). "\c" has no special meaning as an escape so it is interpreted as "c".
"\content\hs\gj\home.css"
Ends up the same as:
"contenthsgjhome.css"
So there are no backslashes for .replace() to find.
(Note that if you do have escaped backslashes in a string literal like "\\" that is part of the literal syntax only and once interpreted the resulting string has only one backslash "\".)
Perhaps if you could explain what you mean by "it's just the output by FS" somebody could offer more advice. This is a common problem when JSP/ASP/PHP/etc outputs JS code - the escaping needs to happen in the JSP/ASP/PHP/etc code before the JS interpreter sees it.
yourstring.split(String.fromCharCode(92)).join('/')

JavaScript Regex match returns null or undefined

var url_pattern = new RegExp("(?:http| https)://(www.|.*)someurlhere[.]com/\d\d\d\d/\d\d/\d\d/.*/", "i");
var url=window.location; //or could be document.URL both don't work
url.match(url_pattern);
why does it return null, or undefined but when i throw the Regex into a check it works perfect and i just want to make sure the URL matches
You have issues with your slashes and an extra space before https and some period characters not escaped properly either.
When using the new RegExp("string") format, you have to double escape any backslash. It's much easier to use the /regexhere/ syntax because you don't have to double escape the backslash used in so many regex rules.
Also, a string has a regex method called .match(). The regex itself has a method called .test() or .exec(). I would suggest this:
var url_pattern = /(?:http|https):\/\/(www\.|.*)someurlhere\.com\/\d\d\d\d\/\d\d\/\d\d\/.*\//i;
window.location.href.match(url_pattern);
If you want to stay with the other way of declaring it, you would escape every backslash like this:
var url_pattern = new RegExp("(?:http|https)://(www\\.|.*)someurlhere[.]com/\\d\\d\\d\\d/\\d\\d/\\d\\d/.*/", "i");
window.location.href.match(url_pattern);
While you should consider using the /regexhere/ syntax suggested by jfriend00, you can also make your RegExp work with the RegExp.new syntax. The problem is that you're within a string so any backslashes you have are considered to be escape character for the string itself, not for the RegExp. To work around this issue you should use a double backslash. Your RegExp should be changed to:
new RegExp("/(?:http|https)://(www.|.*)someurlhere[.]com/\\d\\d\d\\d/\\d\\d/\\d\\d/.*/", "i");`
You may also want to make some other changes to your RegExp as well. For instance, I would suggest using \\. (again note the double escape for use within a string) to match periods instead of using [.].

Categories