adding escape character to a string in javascript - javascript

<html>
<body>
<p id="demo"></p>
<script>
var x = 'It\'s \#lright';
var y = "We are the so-called \"Vikings\" from the north.";
var i;
var s = "";
var z = "Thi$ is * a# demo";
var patt = "[^A-Za-z0-9\\s]";
for(i=0;i<z.length;i++){
if(z[i].match(patt)){
s+= "\\"+z[i];
}
else{
s+= z[i];
}
}
document.getElementById("demo").innerHTML = x + "<br>" + y + "<br>" + s;
</script>
</body>
</html>
The output for the above script I get is :
It's #lright
We are the so-called "Vikings" from the north.
Thi\$ is \* a\# demo
I don't know why for the strings x and y, if I add any special character followed by '\' (backslash), strings are displayed as it is with the special characters. But when I do it to string s by appending '\' before each special character, the string gets displayed with '\' preceding the special characters.
Can someone explain me this? And also please tell me how to add '\' before each special character in such a way that when I print the string I only see the special characters (not with '\' prepended in front of them as happening now)?

why for the strings x and y, if I add any special character followed by '\'(backslash), strings are displayed as it is with the special characters
Because the escape character is part of string literal syntax, and you create x and y with string literals.
When the JavaScript source code is parsed into a string primitive, the escape sequences are converted to the characters they represent.
But when I do it to string s by appending '\' before each special character
Because then you aren't using string literals. "\\" is a string literal and the escape character followed by the backslash becomes a backslash in the data of the string primitive.
When you concatenate that with another string primitive, you are no longer at the parsing source code stage, you have a backslash in the data.
And also please tell me how to add '\' before each special character in such a way that when I print the string I only see the special characters(not with '\' appended in front of them as happening now)?
Do nothing. The data already has the special characters in it.
It doesn't make sense to take something which already exists in the form you want, and then modify it to get the form you want.

The backslash character is the indicator of a string escape character. When it is found in a string, the JavaScript runtime knows that the character that will follow it dictates what actual character to escape. If you just want to include a single backslash, then you'll have to provide the escape code for that, which is two backslashes.
console.log("\"This string has double quotes embedded within double quotes\"");
// If we want to output a single backslash, we need to escape with with \\
// So, if we want to produce two of them, we need \\\\
console.log("The escape code for a \\ is \\\\");
console.log("The escape code for a \' is \\'");
console.log("The escape code for a \" is \\\"");
Now, it's important to distinguish a "JavaScript" string escape sequence with an HTML entity code.
If you take a JavaScript string that includes JavaScript escape characters and send that string to be parsed by the HTML parser, the escape sequences will have already been processed and the HTML parser will be receiving the result of that work. The HTML parser will just render the actual characters that were passed as it normally would.
The JavaScript escape characters only have meaning when processed by the JavaScript runtime, not the HTML parser:
var x = "This will be split over two lines when processed by the JavaScript runtime, \n\nbut the escape code will will just cause normal carriage return white space for the HTML parser";
var y = "\"To escape or not to escape\"";
// Escape code will be parsed and result in two groups of text
alert(x);
// Here, the result of the escaping will be passed to the HTML parser for further processing
// But here, the new line characters embedded within the string will be treated as all exteraneous
// white space in an HTML document is - - it will be normalized down to a single space.
document.querySelector("#d1").innerHTML = x;
document.querySelector("#d2").innerHTML = y;
<div id="d1"></div>
<div id="d2"></div>

Related

How to differentiate " and \" in Javascript

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);

JavaScript: Escaping RegEx in string literals, for use in match()/search() [duplicate]

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 /.

JSON stringify and use of \

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.

ES6: Bad character escape sequence creating ASCII string

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}`

JavaScript - What is correct way for replace "\" charcter with "/" in RegExp

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.)

Categories

Resources