Hay veces en que la función de javascript escape() no es suficiente, como por ejemplo si hay que codificar ‘?’. No sé exactamente cuando ni donde encontré esta función que imita el urldecode de PHP pero migrada a javascript, espero que les sea tan útil como a mi.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | function urlencode( str ) { var histogram = {}, histogram_r = {}, code = 0, tmp_arr = []; var ret = str.toString(); var replacer = function(search, replace, str) { var tmp_arr = []; tmp_arr = str.split(search); return tmp_arr.join(replace); }; // The histogram is identical to the one in urldecode. histogram['!'] = '%21'; histogram['%20'] = '+'; // Begin with encodeURIComponent, which most resembles PHP's encoding functions ret = encodeURIComponent(ret); for (search in histogram) { replace = histogram[search]; ret = replacer(search, replace, ret) // Custom replace. No regexing } // Uppercase for full PHP compatibility return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) { return "%"+m2.toUpperCase(); }); return ret; } |






Escribe un comentario
You must be logged in to post a comment.