JSON stringify and use of \ - javascript

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.

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

adding escape character to a string in 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>

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

Javascript replace function using regular expressions

I am trying to use javascript's replace function to replace a string. But it just replaces the first instance. So when I use regular global expressions,
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/|/g, ';');
I get: http://jsfiddle.net/m8UuD/196/
I want to get:
moaning;yes you;hello test;mission control;com on
Simply escape the pipe :
'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
Here you'll find the list of regex special characters that you should generally escape.
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
You could also use .split() and .join():
'moaning|yes you|hello test|mission control|com on'.split('|').join(';')
You need to escape the '|' like:
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
http://jsfiddle.net/PM4PT/
Many characters are reserved because have a special meaning in a regular expression, so to use one of them you need to "escape" it by placing a backslash \ right before the special character. These are:
( start of a sub-expression
) end of a sub-expression
{ start of repetition range
} end of a repetition range
[ start of a character set
] end of a character set
+ one or more repetitions
* zero or more repetitions
^ start of string
$ end of string
| "or" connection between alternatives
\ start of special code or escape
/ start or end of regexp pattern
For example a regular exprerssion to match all open square bracket is /\[/ (note the backslash). If you need to look for a backslash you must but a backslash in front of it (so doubling it).
Unfortunately there is no predefined Javascript function for "escaping" all special characters.

Categories

Resources