javascriptstringparsingescapingtemplate-literals

Escaping, unicode, character escapes while parsing/logging string in javascript


i got a string, which is from user input, i store it in a variable say, str

let str = "some user generated better string that contains unicode escapes \u1451 \u3516 with some otehr escapes \n \t \r \b \\ / and so on";

i need to print the text as is, so that it exactly matches the user provided string, i am able to achive parsing of \n \t etc using replace, the problem causing ones are \b trying to replace is also replaces the surroundings of words with \\b and i am even unable to match for \u to replace to to escape, it gets converted to its respective character, the moment its stored as string

i got to know about String.raw, but that only seems to work with template literals, using

String.raw`${str}`

does escape others, but again those unicode characted gets converted to their respective char, and unable to get escaped.


Solution

  • Strings received directly from user inputs (HTML elements, terminal, and such) are raw strings already. They don't need extra processes to be displayed on the terminal exactly as the user typed it.

    Your issue comes up when you write something like this:

    let str = "some user generated better string that contains unicode escapes \u1451 \u3516 with some otehr escapes \n \t \r \b \\ / and so on";
    console.log(str);
    

    You can't convert a string object to a raw string. Because JavaScript's parser converts all escape characters in a string into the actual characters they represent. And the parsed string is stored what is stored in memory.

    You need to make str already a raw string directly if you want it to display in the terminal exactly as you made it:

    let str2 = String.raw`some user generated better string that contains unicode escapes \u1451 \u3516 with some otehr escapes \n \t \r \b \\ / and so on`;
    console.log(str2);
    

    You can't make a raw string this way:

    String.raw`${str}`
    

    because ${str} would be substituted with whatever value is stored in str. String.raw wouldn't give you a raw string version of str if you inert it through template substitution.