Javascript equivilant of PHP's urlencode


/ Published in: JavaScript
Save to your folder(s)

Not our code, cribbed from the internet, authors accredited


Copy this code and paste it in your HTML
  1. function urlencode (str) {
  2. // http://kevin.vanzonneveld.net
  3. // + original by: Philip Peterson
  4. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  5. // + input by: AJ
  6. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  7. // + improved by: Brett Zamir (http://brett-zamir.me)
  8. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  9. // + input by: travc
  10. // + input by: Brett Zamir (http://brett-zamir.me)
  11. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  12. // + improved by: Lars Fischer
  13. // + input by: Ratheous
  14. // + reimplemented by: Brett Zamir (http://brett-zamir.me)
  15. // + bugfixed by: Joris
  16. // + reimplemented by: Brett Zamir (http://brett-zamir.me)
  17. // % note 1: This reflects PHP 5.3/6.0+ behavior
  18. // % note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
  19. // % note 2: pages served as UTF-8
  20. // * example 1: urlencode('Kevin van Zonneveld!');
  21. // * returns 1: 'Kevin+van+Zonneveld%21'
  22. // * example 2: urlencode('http://kevin.vanzonneveld.net/');
  23. // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
  24. // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
  25. // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
  26. str = (str + '').toString();
  27.  
  28. // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  29. // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  30. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
  31. replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.