What's the best JavaScript URL decode utility? Encoding would be nice too and working well with jQuery is an added bonus.
I've used encodeURIComponent() and decodeURIComponent() too.
Here is a complete function (taken from PHPJS):
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
用这个
unescape(str);
我不是一个优秀的JS程序员,尝试了所有,而且效果很棒!
decodeURIComponent(mystring);
您可以使用以下代码获取传递的参数:
//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
或通过这种单线获取参数:
location.search.split("your_parameter=")[1]
//How decodeURIComponent Works
function proURIDecoder(val)
{
val=val.replace(/\+/g, '%20');
var str=val.split("%");
var cval=str[0];
for (var i=1;i<str.length;i++)
{
cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
}
return cval;
}
document.write(proURIDecoder(window.location.href));
如果您负责使用urlencode在PHP中编码数据,则PHP的rawurlencode可与JavaScript的encodeURIComponent一起使用,而无需替换+字符。
这是我使用的:
在JavaScript中:
var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);
var decoded_url = decodeURIComponent(encoded_url);
在PHP中:
$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);
$decoded_url = url_decode($encoded_url);
您也可以在这里在线尝试:http : //www.mynewsfeed.x10.mx/articles/index.php?id=17
var uri = "my test.asp?name=ståle&car=saab";
console.log(encodeURI(uri));
decodeURIComponent()
很好,但是您永远不要encodeURIComponent()
直接使用它。这未能逃脱保留字符像*
,!
,'
,(
,和)
。请查看RFC3986(在此定义),以获取更多信息。Mozilla开发人员网络文档提供了很好的解释和解决方案。说明...
为了更严格地遵守RFC 3986(保留!,',(,)和*),即使这些字符没有正式的URI分隔用法,也可以安全地使用以下内容:
解...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
如果不确定,请在JSBin.com上查看有效的演示示例。将此与直接使用的JSBin.comencodeURIComponent()
上的不良演示进行比较。
好的代码结果:
thing%2athing%20thing%21
错误代码来自encodeURIComponent()
:
thing*thing%20thing!
文章标签:javascript , jquery , urldecode , urlencode
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!