1

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

PHP User
  • 2,350
  • 6
  • 46
  • 87
  • Just use single quotes or backticks? `'"'` or `\`"\``, or escape it in double quotes `"\""` – pilchard Nov 28 '21 at 14:22
  • 1
    You may want to reference this answer regarding encoding issues: https://stackoverflow.com/questions/53739238/utf8-encoding-issue-with-laravel – GenericUser Nov 28 '21 at 14:31

3 Answers3

1

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);
GenericUser
  • 3,003
  • 1
  • 11
  • 17
1

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

Yash Sonalia
  • 378
  • 2
  • 8
  • no not yet trying to figure out the issue while inserting into MySQL – PHP User Nov 28 '21 at 15:20
  • 1
    logging the result will output only 1 backslash but it got inserted with the backslash into MySQL so I had to edit it to be `replace('“', '\\\u201c')` and the other replace statement as well. Thanks a lot for your effort I really appreciate it – PHP User Nov 28 '21 at 15:36
0

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42