Search code examples
javascriptescaping

Count the length of a string with special chars in Javascript


So, I have a string like this

"v\xfb\"lgs\"kvjfywmut\x9cr"

and I want to find out the size of it, in Javascript. The thing is that if I copy it to console, the console will unescape the whole string. Will transform it to:

"vû"lgs"kvjfywmutr"

I don't want this to happen. Any tips/tricks?


Solution

  • If you want the number of source characters (including the escape characters), there's no programmatic way to determine that, you'd have to do it by looking at the source code and counting.

    The reason there's no way to do that programatically that once it's a string, it's a string, and there are many, many, many different ways the same string can be written using escape sequences.

    For instance, these all define the same string:

    var s1 = "v\xfb\"lgs\"kvjfywmut\x9cr";
    var s2 = 'v\xfb"lgs"kvjfywmut\x9cr';
    var s3 = "\x76\xfb\"lgs\"k\x76jfywmut\x9cr";
    

    ...and yet as you can see, the number of source characters differs.