Search code examples
javascriptunicodeescapingbackslash

Javascript How to escape \u in string literal


Strange thing...

I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand).

Example

var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');

The string somewhere contains a backslash followed by a character. It's too late to escape the backslash at this point, so I have to escape these special characters individually like

username = username.replace(/\t/ig, 't');

However, that does not work in the following scenario:

var username = "MYDOMAIN\ulrike";

\u seems to introduce a unicode character sequence. \uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\u/ig,'u') comes too late.

Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? It seems a similar issue with \b like in "MYDOMAIN\bernd".


Solution

  • I have a string literal that is passed to my source code

    Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. Something like

    <div id="myServerData">
       MYDOMAIN\tom
    </div>
    

    and you retrieve it so

    alert(document.getElementById("myServerData").innerText);
    

    IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. This goes for whether you are injecting it in script or HTML