0

I have some server side code in PHP which looks like this

$var2 = htmlspecialchars($var1);

For example,

"It's Monday" gets converted to "It's Monday"

I am not able to decode the text back in javascript using the function unescape.

unescape("It's Monday") // returns "It's Monday"

How can i decode this in javascript to get the original string back, apart from using replace (because this way i'd have to manually handle all special cases) ?

Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
  • Why are you using `htmlspecialchars` in the first place? `unescape` doesn't work, since you haven't escaped anything. – kba Jul 20 '14 at 18:35
  • My php code renders a page, javascript handles the client side code. Thus using `htmlspecialchars` and not escape. – Ankit Rustagi Jul 20 '14 at 18:38
  • @AnkitRustagi That doesn't really explain the use of `htmlspecialchars`. What you're doing is not uncommon, yet I've never had to use `htmlspecialchars`. – kba Jul 20 '14 at 18:52
  • @kba My `PHP` code embeds a `JSON` string (which is encoded using `htmlspecialchars`) in the HTML DOM, which is used by my `Javascript` code. Is there any other alternative to this approach ? – Ankit Rustagi Jul 20 '14 at 19:17
  • Why are you encoding your JSON with `htmlspecialchars`? I don't see a reason for that. – kba Jul 20 '14 at 20:38

2 Answers2

1

You can assign the html-encoded text to an dummy element and get back it's text, to do this:

$('<span/>').html("It&#039;s Monday").text()

returns "It's Monday"

Note: The above does not modify the DOM (unlike I said before I edited the answer)

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • Thanks, but this looks like a hack (might get stuck in my code review :p), is there any other way ? – Ankit Rustagi Jul 20 '14 at 18:39
  • @AnkitRustagi - This is indeed a hacky way of doing it. The *right* way will involve capturing `&.+;` in the string and replacing with the appropriate character (probably using a table of characters). – techfoobar Jul 20 '14 at 18:41
1

You'll have to encode your text using urlencode in PHP if you want to decode it again using JavaScript's unescape.

// PHP
urlencode("It's Monday") // returns "It%27s%20Monday"

// JavaScript
unescape("It%27s%20Monday") // returns "It's Monday"
Hauke P.
  • 2,695
  • 1
  • 20
  • 43