2

Context

I'd like to convert strings in javascript to its unicode representation so I can do funky things with it.

Some examples of what I mean:

I can write

eval('\u0076\u0061\u0072 \u006a \u003d \u0022\u0068\u0069\u0022');
// This is `var j = "hi"`.
// For clarity, I kept \u0020 as a space.

I can also write

eval('\u0076\u0061\u0072 \\u006a \u003d \u0022\\u0068\\u0069\u0022');
// Here I've escaped the backslash
// on the variable name and string

These are equivalent, and both result in j == 'hi'.

What's cool is that I can do the following:

var val = '\\u0068\\u0069';
var key = '\\u006a';
eval('\u0076\u0061\u0072 ' + key + ' \u003d \u0022' + val +  '\u0022');

This allows me to generate the values of key and val programmatically, using the following:

function uEncode(str) {
    var hex, i;
    var result = "";
    for (i=0; i < str.length; i++) {
        hex = str.charCodeAt(i).toString(16);
        result += "\\u" + ("000"+hex).slice(-4);
    }
    return result;
}

Question

What I would like to do is to be able to do the following:

eval(uEncode('var j = "hi"'));

This doesn't work because uEncode will escape the backslashes on the var keyword (\u0076\u0061\u0072) and the following characters: = (\u003d), (\u0020), and " (\u0022).

If the the backslashes on the unicode for any javascript keyword or symbol is escaped, eval throws a syntax error.

Unfortunately, this isn't something that can be resolved with a simple

eval(unescape(uEncode('var j = "hi"')));

Is there any way to accomplish this?

1
  • Smells like fun to me. Commented Nov 30, 2015 at 23:37

1 Answer 1

1
eval(JSON.parse('"'+uEncode('var j = "hi"')+'"'))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.