DevKB
Web Development Knowledge Base
HOME | TOP 20 | WRITE AN ARTICLE |
Sections :



RSS RSS Feed

You too, please publish your useful code snippets in any programming language :
write an article !


Valid HTML 4.0 Transitional

Plateforme d'envoi de gros fichiers en ligne
Dépannage site web
Blog infogérance
Hébergement e-mail

Olivier Ligny - - 06/11/2008 - vue 28240 fois

URLEncode() en JavaScript

En javascript il n'existe pas de fonction universelle pour encoder des valeurs passées en paramètres dans une URL.
Les fonctions escape(), encodeURIComponent, etc, ne fonctionnent pas toujours correctement notamment pour les chaines non-ASCII.

Voici une fonction qui donne le même résultat que la fonction urlencode() de PHP :

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
}
}
return output;
}

Source : http://cass-hacks.com/articles/code/js_url_encode_decode/

 




Write a comment :
Your name :     E-mail (optional) :

AntiSpam : what animal is visible on this picture ? :

Nos partenaires : iPhone 8 Cases & Protection