Javascript replace unescaped slash - javascript

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('/')

Related

Does regex syntax provide a way of escaping a whole string, rather than escaping characters one by one?

If I want to find a reference to precisely the following string:
http ://www.mydomain.com/home
within a more complex regex expression.
Is it possible to escape the whole sequence instead of escaping each / and . character individually? To get something more readable than
/http:\/\/www\.mydomain\.com\/home/
In the regex parsing site https://regexr.com/ , if I type the url in and set a regex to
/(http ://www.mydomain.com/home)/
, it appears to recognize the string, yet declares an error:
Unescaped forward slash. This may cause issues if copying/pasting this expression into code.
So I'm confused about this issue.
It appears that regex does not offer such a syntax, at least for Javascript. It is possible, however, to proceed as follows:
use a string and automatically escape all the special characters in it,
as indicated here: Javascript regular expression - string to RegEx object
concatenate that string with strings representing the rest of the expression you want to create
transform the string into a regex expression as indicated in Escape string for use in Javascript regex .

Regex match with '\' slash and replace with '\\'?

I was converting normal string in to latex format.So i was created the latex code match and replace the \ single slash into \\ double slash.why the i need it Refer this link.I tried Below code :
function test(){
var tex="$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$";
var tex_form = tex.replace("/[\\\/\\\\\.\\\\]/g", "\\");
document.getElementById('demo').innerHTML=tex_form;//nothing get
}
test();
<p id="demo"></p>
Not getting any output data.But the match in this link
i wish to need replace the \ into \\
There are these issues:
The string literal has no backslashes;
The regular expression is not a regular expression;
The class in the intended regular expression cannot match sequences, only single characters;
The replacement would not add backslashes, only replace with them.
Here you find the details on each point:
1. How to Encode Backslashes in String Literals
Your tex variable has no backslashes. This is because a backslash in a string literal is not taken as a literal backslash, but as an escape for interpreting the character that follows it.
When you have "$$\left...", then the \l means "literal l", and so the content of your variable will be:
$$left...
As an l does not need to be escaped, the backslash is completely unnecessary, and these two assignments result in the same string value:
var tex="$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$";
var tex="$$left[ x=left({{11}over{2}}+{{sqrt{3271}}over{2,3^{{{3}over{2} $$";
To bring the point home, this will also represent the same value:
var tex="\$\$\l\e\f\t\[\ \x\=\l\e\f\t\(\{\{\1\1\}\o\v\e\r\{\2\}\}\+\{\{\s\q\r\t\{\3\2\7\1\}\}\o\v\e\r\{\2\,\3\^\{\{\{\3\}\o\v\e\r\{\2\}\ \$\$";
If you really want to have literal backslashes in your content (which I understand you do, as this is about LaTeX), then you need to escape each of those backslashes... with a backslash:
var tex="$$\\left[ x=\\left({{11}\\over{2}}+{{\\sqrt{3271}}\\over{2\\,3^{{{3}\\over{2} $$";
Now the content of your tex variable will be this string:
$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$
2. How to Code Regular Expression Literals
You are passing a string literal to the first argument of replace, while you really intend to pass a regular expression literal. You should leave out the quotes for that to happen. The / are the delimiters of a regular expression literal, not quotes:
/[\\\/\\\\\.\\\\]/g
This should not be wrapped in quotes. JavaScript understands the / delimiters as denoting a regular expression literal, including the optional modifiers at the end (like g here).
3. Classes are sets of single characters
This regular expression has unnecessary characters. The class [...] should list all individual characters you want to match. Currently you have these characters (after resolving the escapes):
\
/
\
\
.
\
\
It is overkill to have the backslash represented 5 times. Also, in JavaScript the forward slash and dot do not need to be escaped when occurring in a class. So the above regular expression is equivalent to this one:
/[\\/.]/g
Maybe this is, or is not, what you intended to match. To match several sequences of characters, you could use the | operator. This is just an example:
/\\\\|\\\/|\\\./g
... but I don't think you need this.
4. How to actually prefix with backslashes
It seems strange to me that you would want to replace a point or forward slash with a backslash. Probably you want to prefix those with a backslash. In that case make a capture group (with parentheses) and refer to it with $1 in this replace:
tex.replace(/([\\/.])/g, "\\$1");
Note again, that in the replacement string there is only one literal backslash, as the first one is an escape (see point 1 above).
why the i need it
As the question you link to says, the \ character has special meaning inside a JavaScript string literal. It represents an escape sequence.
Not getting any output data.But the match in this link
The escape sequence is processed when the string literal is parsed by the JavaScript compiler.
By the time you apply your regular expression to them, they have been consumed. The slash characters only exist in your source code, not in your data.
If you want to put a slash character in your string, then you need to write the escape sequence for it (the \\) in the source code. You can't add them back in with JavaScript afterwards.
Not sure if I understood the problem, but try this code:
var tex_form = tex.replace("/(\\)/g","\\\\");.
You need to use '(' ')' instead of '['']' to get a match for output.

typing a single forward slash in javascript

I want to generate the string "\" in Javascript but couldn't seem to do it. If I only write "\", I would get compile time error because " itself is escaped. But if I do "\\", I would get two slashes as the output. So how do I generate a string with a single forward slash?
The character / is a slash. The character \ is a backslash.
Backslash \ is used as an escape character for strings in JavaScript, and in JSON. It is required for some characters to remove ambiguity from string literals. This string is ambiguous:
'He's going to the park'
There are three single quote ' marks, and the parser doesn't know what is part of the string and what isn't. We can use a backslash to escape the one that we want to represent the character ' instead of the close of the string literal (also ').
'He\'s going to the park'
Now, if the backslash has special meaning, how do we represent a literal backslash \ character in the string? By simply escaping the backslash \ with a backslash \.
'C:\\DOS\\command.com' // In memory this is: C:\DOS\command.com
Remember that this escaping is only for the text representation of strings in code or JSON. The code is parsed and the strings in memory are what we would expect, with all escaping resolved to the proper characters.
Now your question asks about JSON and makes the assumption that this is incorrect:
I am writing '\' as the key to a JSON package. The result is something like "READY_TO_PRINT_DATE":"/\\Date(1403911292:981000+420)\\/".
JSON requires the same escaping as you find in JavaScript, and for the same reason... to remove ambiguity from strings. The JSON-version of the string /\\Date(1403911292:981000+420)\\/ is how you would properly represent the actual string /\Date(1403911292:981000+420)\/.
I hope this helps clears up some of your confusion.
you can escape the slash:
myvar = "\\";

JSON to JavaScript escape character Query

I am of the understanding that if I am trying to stringify quotes (' and "), i need to escape them but I can't explain the following results when I tried the same out in firebug:
1. >> JSON.stringify({foo: "a"a'a"});
SyntaxError: missing } after property list
Inference: This is expected since I didn't escape " and '
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
Inference/Question: Will the JSON string also show the escape character before " and why it works without escaping the single quote
Also JSON throws an error when I try to parse the output string generated above back to JS object ?
>>> JSON.parse("{"foo":"a\"a'a"}")
SyntaxError: missing ) after argument list
Finally Explain results below: Basically if I escape the single quote once, it doesn't show up in the output string but if I escape twice, it does
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
Basically I am trying to understand when and how I need to escape single and double quotes when converting to and from JSON.
Thanks for your help
EDIT:
Thanks for the replies .
The first 2 queries are clear. So I only need to escape the quotes I am using to enclose the string ( in my case ") and escape any escape characters itself in the string. Other than these 2, I don't need to escape any other chars?
I am not clear on the last query. If I just increase the escape characters before ', why does it shows even number of escape chars in the output . For eg
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
>>> JSON.stringify({foo: "a\"a\\\'a"});
"{"foo":"a\"a\\'a"}"
The format given by your JavaScript interpreter here is a little misleading when it outputs the following:
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
The interpreter is adding the double quotes on the outside without doing any of the necessary escaping to make the result a valid string literal, so what this is actually trying to say is that the result of the expression is a string that contains {"foo":"a\"a'a"} (where every character there is literal, including the backslash). If you were going to write this as a JavaScript string literal it would be one of the following:
With double quotes: "{\"foo\":\"a\\\"a'a\"}"
With single quotes: '{"foo":"a\\"a\'a"}'
The above strings are exactly identical, they are just represented differently based on which external quote is used. You should be able to pass either of those strings to JSON.parse and get an object equivalent to what you started with.
Hopefully this will also help to clarify as to why the single quote isn't escaped, as shown above you only need to escape the type of quote that is used for the string literal (so escape internal double quotes if double quotes surround the string, and escape internal single quotes when single quotes are around the string).
So the errors being thrown is because the string is being ended. So any other characters that follow are attempted to be parsed but aren't able to be. Hence the errors.
So because you start with a quotation mark ("), using an apostrophe (') isn't ending the string. It's within the string, because your string is expected to end with another quotation mark.
If you want to include the same character that the string is defined within, it will need to be escaped. E.g. " and he said \"what a great day!\" to the other boy"
No need to escape single quotes inside of double quotes, or double quotes inside of single quotes.
You do need to escape like quotes within like quotes -- these are all valid syntax:
var a = "Testing '1234'";
var b = 'Testing "1234"';
var c = "Testing \"1234\"";
var d = 'Testing \'1234\'';
Second piece, on JSON stringification, the double quotes you see output here:
JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
are just an output within whatever console or repl you are using. Technically those should be output as single quotes.
At any rate...
var s = JSON.stringify({foo: "a\"a'a"});
JSON.parse(s);
...will most definitely output a valid object.
Your first inference is correct; you need to escape any special characters (Quotation marks, in this case) that you want to appear in your final string. If you don't, then the browser will try to parse the string as-is, and will fail miserably because of mismatched quotes.
This is the same reason you get an error when you're parsing the string; the parser can't account for the mismatched quotes.
For the last behaviour you were having trouble with, you're not really escaping the quote twice; you're escaping the escape character.

Javascript: unable to escape backslash in IE

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.

Categories