Let's say I have a string like this '"\"'. The length of this string is 2. So I wonder if there's any way I can differentiate the first " and the second \"? Thanks.
I'm trying to parse a string and I want to turn on/off a flag when " is encountered, but ignore the \".
It's not possible. The two characters are equal to each other, because the backslash gets interpreted as an unnecessary escape character, and gets discarded:
const str = '"\"';
console.log(str[0] === str[1], str.length);
If you wanted to put a literal backslash into the string, either put two backslashes in there:
const str = '"\\"';
console.log(str.length);
Or use String.raw, in which (nearly) every character gets interpreted literally, without escaping:
const str = String.raw`"\"`;
console.log(str.length);
In Javascript, when I put a backslash in some variables like:
var ttt = "aa ///\\\";
var ttt = "aa ///\";
Javascript shows an error.
If I try to restrict user in entering this character, I also get an error:
(("aaa ///\\\").indexOf('"') != -1)
Restricting backslashes from user input is not a good strategy, because you have to show an annoying message to the user.
Why am I getting an error with backslash?
The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
In order to output a literal backslash, you need to escape it. That means \\ will output a single backslash (and \\\\ will output two, and so on). The reason "aa ///\" doesn't work is because the backslash escapes the " (which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\" won't work, because the last backslash again escapes the quote.
Just remember, for each backslash you want to output, you need to give Javascript two.
You may want to try the following, which is more or less the standard way to escape user input:
function stringEscape(s) {
return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}
This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.
You have to escape each \ to be \\:
var ttt = "aa ///\\\\\\";
Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.
because you had to show a message to user that user can't give a name which has (\) character.
I think the scenario is like:
var user_input_name = document.getElementById('the_name').value;
Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.
If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.
I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:
var ttt = "aa ///\";
Hence, we assume the asker having problem with escaping.
If you want to simulate, you code must be valid at first place.
var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.
alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
Now, you only need to do is
var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
do_something_else();
}
Edit: I used [] to quote text to be shown, so it would be less confused than using "".
The backslash \ is reserved for use as an escape character in Javascript.
To use a backslash literally you need to use two backslashes
\\
If you want to use special character in javascript variable value, Escape Character (\) is required.
Backslash in your example is special character, too.
So you should do something like this,
var ttt = "aa ///\\\\\\"; // --> ///\\\
or
var ttt = "aa ///\\"; // --> ///\
But Escape Character not require for user input.
When you press / in prompt box or input field then submit, that means single /.
assert(JSON.stringify(searchForMatches(searchData,['cats']))==='["catcode.io","catgifs.co"]',"The result should be '[\"catcode.io\",\"catgifs.co\"]'");
Why do I need the use of \ at the end multiple times? It throws an error otherwise. Is it specific to JSON.stringify and/or when/how should I go about about using it in future instances?
\ is an escape operator. It prevents the language from parsing the next char as syntax relevant, so without it your string stops at the next " after the first " which starts the string.
The backslash is a JavaScript operator used within a string for escaping a special character.
In your case it is escaping a quotation. See this example:
// in this case it escapes the " symbol because that would end the string.
var x = "\"";
This is the same as:
// in this case you don't need to escape it because
// the string begins with the apostrophe instead of the " character
var x = '"';
In both cases console.log(x); will print a single quote character.
Here's my code:
let padded = "03";
ascii = `\u00${padded}`;
However, I receive Bad character escape sequence from Babel. I'm trying to end up with:
\u0003
in the ascii variable. What am I doing wrong?
EDIT:
Ended up with ascii = (eval('"\\u00' + padded + '"'));
What am I doing wrong?
A unicode escape sequence is basically atomic. You cannot really build one dynamically. Template literals basically perform string concatenation, so your code is equivalent to
'\00' + padded
It should be obvious now why you get that error. If you want to get the corresponding unicode character you can instead use String.fromCodePoint or String.fromCharCode:
String.fromCodePoint(3)
If you want a string that literally contains the character sequence \u0003, then you just need to escape the escape character to produce a literal backslash:
`\\u00${padded}`
I defined a function in JavaScript that replace all -, _, #, #, $ and \ (they are possible separators) with / (valid separator).
My goal is any string like "1394_ib_01#13568" convert to "1394/ib/01/13568"
function replaceCharacters(input) {
pattern_string = "-|_|#|#|$|\u005C"; // using character Unicode
//pattern_string = "-|_|#|#|$|\"; // using original character
//pattern_string = "-|_|#|#|$|\\"; // using "\\"
//pattern_string = "\|-|_|#|#|$"; // reposition in middle or start of string
pattern = new RegExp(pattern_string, "gi");
input = input.replace(pattern, "/");
return input;
}
My problem is when a string with \ character send to function result is not valid.
I tried use Unicode of \ in define pattern, Or use \\\ instead of it. Also I replaced position of it in pattern string. But in any of this situation, problem wasn't solved and browser return invalid result or different error such as:
SyntaxError: unterminated parenthetical ---> in using "\u005C"
SyntaxError: \ at end of pattern ---> in using "\\"
Invalid Result: broken result in 2 Line or replace with undefined character based on input string (the character after "\" determine result)
---> in reposition it in middle or start of pattern string
var pattern_string = "-|_|#|#|\\$|\\\\";
You have to escape the slash once for the pattern, so it'll try to match the literal character:
\\
Then, escape each slash again for the string literal:
"\\\\"
Also note that I added an escape for the $. To match a dollar sign literally, it'll needs to be escaped as well, since it normally represents an anchor for the "end of the line/string."
You can also use a Regex literal to avoid the string, using only the escape sequences necessary for the pattern:
var pattern = /-|_|#|#|\$|\\/gi;
And, as you're matching only single characters, you can use a character class instead of alternation:
var pattern = /[-_##\$\\]/gi;
(Just be careful with the placement of the - here. It's fine as the first character in the class, but can represent a range of characters when placed in the middle. You can also escape it to ensure it doesn't represent a range.)