28

I have a html text. I had encoded it in php using urlencode function. I want to decode that text in the javascript. when i use unescape function in javascript it replaces all the special characters back but sapce is replaced by '+'. how can i do it correctly so that space is replaced as space itself???

Andromeda
  • 12,659
  • 20
  • 77
  • 103

5 Answers5

53

PHP rawUrlEncode() == JavaScript encodeURIComponent()

PHP rawUrlDecode() == JavaScript decodeURIComponent()

Yasen
  • 3,400
  • 1
  • 27
  • 22
  • 2
    be ware that php urlencode is not compatible with javascript so u should use rawUrlEncode instead – Amir Surnay Oct 28 '13 at 13:42
  • Working for me (((PHP))) $msg = array(); $msg['adds'] = rawUrlEncode($complexAddsWithHTMLMarkup); echo json_encode($msg); ......(((jQuery ajax dataType json))) decodeURIComponent(msg.adds); – Coisox Aug 01 '14 at 11:41
  • 4
    Unfortunately, this answer is wrong for some characters. In php `rawurlencode(")") == "%29"` while in javascript `encodeURIComponent(")") == ")"`. – Régis B. Mar 20 '17 at 18:39
  • 2
    @RégisB. To comply to RFC 3986 there is a fix on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent). To the bottom there is a function called `fixedEncodeURIComponent` – Michel Sep 29 '18 at 07:12
16

Try using rawurlencode instead - urlencode does some things differently for "historical" reasons.

See http://us.php.net/manual/en/function.urlencode.php for more information.

Dave
  • 4,375
  • 3
  • 24
  • 30
4

Parenthesis are exceptions to all of what is said in this post.

geek mode on :

false

PHP rawUrlEncode() !== JavaScript encodeURIComponent()

but true

PHP rawUrlEncode() == JavaScript encodeURIComponent()

In other words, there are many special characters that aren't treated as safe in rawurlencode when they are in encodeURIComponent.

davidwebca
  • 435
  • 5
  • 11
3

Try this:

return decodeURIComponent((str + '').replace(/\+/g, '%20'));

Source: http://phpjs.org/functions/urldecode:572

Justo
  • 1,793
  • 1
  • 10
  • 6
0

PHP rawUrlEncode with JS unescape (deprecated but working)

For me decodeURIComponent throw errors sometimes.

mikmikmik
  • 500
  • 1
  • 5
  • 10