Javascript Unicode Escaping Backslash [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I decode a string with escaped unicode?
I'm having a javascript variable, in which i have stored a unicode character.
var value = "\\u53d3\\u5f13\\";
I'm adding the above value dynamically to a div, due to the extra back slash(\\u) proper unicode value is not shown. But if I Change it to single back slash that is \u instead of \\u . The unicode symbol is correctly shown.
In my environment I can not store the value with single back slash. As the response is from the server side..
Is there anyway to replace the double backslash with single backslash to show the proper unicode?
Thanks in Advance

It's not about backslash anymore, it's about what the string literally contains. If you just replaced backslashes, you would just end up with "u53d3u5f13". You can trivially unescape them though (if you don't care that anything \uXXXX will be replaced):
function unescapeUnicode( str ) {
return str.replace( /\\u([a-fA-F0-9]{4})/g, function(g, m1) {
return String.fromCharCode(parseInt(m1, 16));
});
}
var value = "\\u53d3\\u5f13\\";
unescapeUnicode(value);
"叓弓\"

Related

In JavaScript, string '\m' is fully equals to string 'm', why? [duplicate]

This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 2 years ago.
console.log('\d' === 'd'); // true
Character 'd' is not a special character, why javascript want to slice the escape notation.
It's better to keep the escape notation in my view.
When I want to fully match string-'\d' using regular expression, it just impossible!
Taking the following code as an example.
console.log(RE.test('\d')); // it should log true
console.log(RE.test('d')); // it should log false
Unfortunately, you just cannot figure out a regular expression pattern.
You have no reason to escape d in a string and JavaScript ignores it. If you need \d you need to escape the escape character: \\d.
See also Why do linters pick on useless escape character?
\d has a special meaning in regular expressions (a digit character), but also in strings (escaped 'd' character, which is exactly like 'd').
Any / creates an escape sequence in a string. Some are "useful" (\n === new line) and some arguably useless (`'\d' === 'd').
If you want the regex \d, you could
1 - use a regex literal instead : /\d/
2 - escape the \ in the string : '\\d', so that the string containing the two characters \ and d is correctly understood by Javascript.

Single Backslash to double backslash Conversion [duplicate]

This question already has answers here:
JavaScript backslash (\) in variables is causing an error
(5 answers)
Escaping backslash in string - javascript
(5 answers)
Closed 3 years ago.
I want all single backslashes to be converted into double backslash
"C:\Users\MyName\ringtone.mp3" --> "C:\\Users\\MyName\\ringtone.mp3"
But for some reason it returns "C:UsersMyNameingtone.mp3"
So far I have tried the escape() function and the encodeURI() function but they don't work either. Partial of the string comes from nodejs OS Module which only returns with a single backslash on windows (homedir() function).
Here is what I have so far in the function
function normalize(path: string): string {
return path.normalize().replace(/\\/g, '\\');
}
Thanks in Advance
This should work:
var original = 'C:\\Users\\MyName\\ringtone.mp3';
var replaced = original.normalize().replace(/\\/g, '\\\\');
console.log('Original: ' + original);
console.log('Replaced: ' + replaced);
From what I see you had 2 problems:
First, it seems you were initializing your string like this:
var original = 'C:\Users\MyName\ringtone.mp3'
This would make your actual string value C:UsersMyNameingtone.mp3 because a \ character in javascript symbolizes an escape character.
Second, is because the \ character is an escape character, so the '\\' in your replace function is only looking to replace the matching pattern with a single backslash.

How to ignore brackets in a regex [duplicate]

This question already has an answer here:
Escape string for use in Javascript regex [duplicate]
(1 answer)
Closed 3 years ago.
I have a regex that takes a template literal and then matches it against a CSV of conditions and links.
const regex = new RegExp(`^${condition},\/.+`, 'gi');
For example, the variable Sore throat would match
'Sore throat,/conditions/sore-throat/'
I've come across an issue where the template literal might contain brackets and therefore the regex no longer matches. So Diabetes (type 1) doesn't match
'Diabetes (type 1),/conditions/type-1-diabetes/'
I've tried removing the brackets and it's contents from the template literal but there are some cases where the brackets aren't always at the end of the string. Such as, Lactate dehydrogenase (LDH) test
'Lactate dehydrogenase (LDH) test,/conditions/ldh-test/'
I'm not too familiar with regex so apologies if this is simple but I haven't been able to find a way to escape the brackets without knowing exactly where they will be in the string, which in my case isn't possible.
You are trying to use a variable that might contain special characters as part of a regex string, but you /don't/ want those special characters to be interpreted using their "regex" meaning. I'm not aware of any native way to do this in Javascript regex - in Perl, you would use \Q${condition}\E, but that doesn't seem to be supported.
Instead, you should escape your condition variable before passing it into the regex, using a function like this one:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Switching \n with \\n in javascript [duplicate]

This question already has answers here:
How do I handle newlines in JSON?
(10 answers)
Closed 4 years ago.
So I have a string:
var s = "foo\nbar\nbob";
I want the string to become:
"foo\\nbar\\nbob"
How can I replace every \n with a \\n?
I've tried using some for loops, but I can't figure it out.
A simple .replace would work - search for \n, and replace with \\n:
var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, '\\\n')
// ^^ double backslash needed to indicate single literal backslash
);
Note that this results in "a single backslash character, followed by a literal newline character" - there will not be two backslashes in a row in the actual string. It might be a bit less confusing to use String.raw, which will interpret every character in the template literal literally:
var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, String.raw`\
`) // template literal contains one backslash, followed by one newline
);

JSON.parse with newline [duplicate]

This question already has answers here:
How do I handle newlines in JSON?
(10 answers)
Closed 7 years ago.
Why can't you parse a json with a \n character in javascript
JSON.parse('{"x": "\n"}')
However when you do JSON.parse(JSON.stringify({"x" : "\n"})), it is valid.
http://www.jslint.com/ says that {"x": "\n"} is a valid JSON. I wonder what does spec says about this?
Update:
For those who marked this duplicate, this is not the same question as "How to handle newlines in JSON". This question is more about why can't an unescaped newline character allowed in JSON.
JSON.parse('{"x": "\n"}') fails because '{"x": "\n"}' is not a valid JSON string due to the unescaped slash symbol.
JSON.parse() requires a valid JSON string to work.
'{"x": "\\n"}' is a valid JSON string as the slash is now escaped, so JSON.parse('{"x": "\\n"}') will work.
JSON.parse(JSON.stringify({"x" : "\n"})) works because JSON.stringify internally escapes the slash character.
The result of JSON.stringify({"x" : "\n"}) is {"x":"\n"} but if you try to parse this using JSON.parse('{"x":"\n"})' it will FAIL, as it is not escaped. As JSON.stringify returns an escaped character, JSON.parse(JSON.stringify()) will work.
It need to be:
JSON.parse('{"x": "\\n"}')
You must use \\ to escape the character.
Why it's invalid?
It' from rfc4627 specs
All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)." Since a newline is a control character, it must be escaped.
In JavaScript "\n" is not the literal string \n. It is a string containing a newline character. That makes your JSON invalid.
To represent the literal string \n, you need to escape the initial backslash character with another backslash character: "\\n".
You need to escape the "\" in your string (turning it into a double-"\\"), otherwise it will become a newline in the JSON source, not the JSON data.
Try to replace \n with some other characters while parsing and again replace those characters with \n before assigning this value to some control.

Categories