ES6: Bad character escape sequence creating ASCII string - javascript

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

Related

Javascript substring from last backslash char

This is probably a basic syntax question, but I am not able to find a syntax for a backslash character. Following and other syntaxes that I tried are not accepted for this char.
var fileNameSubstring = data.FileName.substring(data.FileName.lastIndexOf('\') + 1, data.FileName.length);
When defining a string in Javascript you can use the backslash (called escape character) to indicate special characters like new line \n.
To actually have a backslash in your string you should use double blackslash \\.
var fileNameSubstring = data.FileName.substring(data.FileName.lastIndexOf('\\') + 1, data.FileName.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>

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

Confused about regular expression code not working

var regex=/\u00E(0|1)/g;
I want to find à or á in the string.
Is this regex correct? Why isnt it working?
It won't work because the Unicode escape sequence \u expects four hexadecimal digits after the sequence like this: \uNNNN where each N is a hexadecimal digit.
Instead use literal characters in the regex like #Jacks soluion, or use #Fabrizio's solution.
Use instead
var regex= /[\u00E0\u00E1]/g;
You're breaking up the Unicode sequence in your expression and an unfinished sequence gets interpreted as a literal '\\u00E'.
That said, you can just put those characters in the expression itself:
var regex = /[àá]/;
regex.text('állo'); // true
Literals need to be explicit. You need
var regex=/\u00E0|\u00E1/g;

javascript: some problem with compiler interpreting // as comments in regex

I've got this regular expression for validating phone numbers
^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$
I dugged it out from my C#/vb library and now i want to translate it into javascript. But it has syntax error (i suspect it is something due to the // characters). my attempt:
$IsPhone = function (input) {
var regex = new window.RegExp("^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$", "");
return regex.test(input.trim());
};
alert($IsPhone("asd"));
Your problem has nothing to do with comments. You're just mixing up the two different ways of creating RegExp objects.
When you create a RegExp object in JavaScript code, you either write it as a string literal which you pass to a RegExp constructor, or as a regex literal. Because string literals support backslash-escape sequences like \n and \", any actual backslash in the string has to be escaped, too. So, whenever you need to escape a regex metacharacter like ( or +, you have to use two backslashes, like so:
var r0 = "^$|^(\\+?|(\\(\\+?[0-9]{1,3}\\))|)([ 0-9./-]|\\([ 0-9./-]+\\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9./-]|\\([ 0-9./-]+\\)))?$";
var regex0 = new RegExp(r0, "");
The forward-slash has no special meaning, either to regexes or strings. The only reason you ever have to escape forward-slashes is because they're used as the delimiter for regex literals. You use backslashes to escape the forward-slashes just like you do with regex metacharacters like \( or \+, or the backslash itself: \\. Here's the regex-literal version of your regex:
var regex1 = /^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.\/-]|\([ 0-9.\/-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.\/-]|\([ 0-9.\/-]+\)))?$/;
from Errors translating regex from .NET to javascript
The backslash character in JavaScript
strings is an escape character, so the
backslashes you have in your string
are escaping the next character for
the string, not for the regular
expression. So right near the
beginning, in your "^(+?, the
backslash there just escapes the + for
the string (which it doesn't need),
and what the regexp sees is just a raw
+ with nothing to repeat. Hence the error.

Categories

Resources