Search code examples
javascriptspecial-charactersencodequotes

How to replace or encode single and right double quotation mark in JavaScript?


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


Solution

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