johnwards
johnwards

Reputation: 1901

decodeURIComponent not decoding a string from a data attribute

I've got a strange issue with decoding an escaped javascript string.

Here is the test code, getting the escaped string from the data attribute doesn't work it just gets printed out raw. The second example works fine.

var emailText = $('#emaildata').data('email-text');
var unescapedEmailText = decodeURIComponent(emailText);
alert(unescapedEmailText);

var emailText2 = "Blah blah edit blah foo\x27\x0a\x0a\x0a\x27\x27\x27";
var unescapedEmailText2 = decodeURIComponent(emailText2);
alert(unescapedEmailText2);

Here is a jsfiddle showing the broken functionality. http://jsfiddle.net/wnegH/2/

I'm sure i'm doing something daft, but what I can't fathom out...

Upvotes: 0

Views: 1632

Answers (2)

Quentin
Quentin

Reputation: 943608

JavaScript escape sequences (such as \x27) have no special meaning in HTML. You need to use character references or real characters instead.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

What you put inside the data-email-text attribute is not a javascript string. So using \x27 inside it, simply means the \x27 string as-is and not the corresponding ASCII character.

Here's an example of how you could achieve the desired effect:

<div id="emaildata" data-email-text="Blah%20blah%20edit%20blah%20foo'%0A%0A%0A'''"></div>

and then:

var emailText = $('#emaildata').data('email-text');
var unescapedEmailText = decodeURIComponent(emailText);
alert(unescapedEmailText);

Obviously the string I have used in the data-email-text attribute was obtained by invoking the encodeURIComponent function on the target string.

Upvotes: 2

Related Questions