Reputation: 2422
I have string contains this “No.”
as you see that's not normal double quotes. I tried to encode it manually by using replace
like this
var stmt = "select “No.”";
stmt = stmt.replace('“', '\u201c');
stmt = stmt.replace('”', '\u201d');
console.log(stmt);
But when I log stmt
I find that nothing changed at all and logs this “No.”
. How can I encode such special characters in Javascript? I'm using sequelize
to insert this statement to the database and need it to be encoded to be displayed correctly inside a JSON string so the final result should be \u201cNo.\u201d
Upvotes: 1
Views: 4874
Reputation: 398
You need to use the escape character \ to prevent JS to interpret "\u201c" and "\u201d" as unicode characters.
Check this:
var stmt = "select “No.”";
stmt = stmt.replace('“', '\\u201c');
stmt = stmt.replace('”', '\\u201d');
console.log(stmt);
Upvotes: 2
Reputation: 25398
1) It is better to replace all characters in a single go use regex /“|”/g
:
var stmt = "select “No.”";
stmt = stmt.replace(/“|”/g, '"');
console.log(stmt);
2) You can also use replaceAll here as:
var stmt = "select “No.”";
stmt = stmt.replaceAll(/“|”/g, '"');
console.log(stmt);
3) You can also replace it using its unicode value as:
var stmt = "select “No.”";
stmt = stmt.replaceAll(/\u201C|\u201D/g, '"');
console.log(stmt);
Upvotes: 0
Reputation: 3230
There's no need to use the unicode references. Just pass in the quotations as normal, within single quotes.
var stmt = "select “No.”";
stmt = stmt.replace('“', '"');
stmt = stmt.replace('”', '"');
console.log(stmt);
Upvotes: 1