How can I parse a javascript string as if entered as text

Viewed 1119

When entering a javascript string, some parsing is applied for escape sequences.
E.g., var foo = "ab\\cd"; will give foo a value of ab\cd.

I need to take some javascript code as a string, and extract a variable value from it, but when I do so, escape sequences are not applied. How can I reapply text parsing as if entering the string value initially.

Here's an example fiddle. It's simple, so I'll include the code here.

HTML:

<a href="javascript:alert('abc\/def');" oncontextmenu="log(this)">Click or right click</a>

Javascript:

function log(el){
  var href = el.getAttribute('href');
  var str = href.split("'")[1];
  alert(str);
}

Clicking the link will alert abc/def, but right clicking will output abc\/def.

How can I make right click alert the same as the left click?

2 Answers
Related