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.
Related
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.
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, '\');
I am having difficulties handling symbol \ in javascript. Strings seems to ignore it, for example alert('a\b') would only alert a.
My goal is to write following function which would give me latex image:
function getLatexImage(tex)
{
return 'http://chart.apis.google.com/chart?cht=tx&chl=' + tex;
}
However calling getLatexImage('\frac{a}{b}') gives me: "http://chart.apis.google.com/chart?cht=tx&chl=rac{a}{b}"
\f is being ignored.
Any suggestions?
\ is an escape character. It starts an escape sequence.
\n is a new line. \t is a tab. An escape sequence that has no special meaning usually gets turned into the character on the RHS (so \b is b).
To have a backslash as data in a string literal you have to escape it:
alert('a\\b');
Use \\. Single slashes are used for special signs (like \n, \t..)
The backslash \ is a escape character in JavaScript and many other programming languages. If you want to output it, you'll need to escape it by itself.
\\a
for example would output \a.
That being said, if you want to use it in an url you should encode it for safety.
%5c
translates to \
You can simply escape it by adding another backslash
'\\b'
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 = "\\";
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);