最好的 JavaScript URL 解码实用程序是什么?编码也很好,与 jQuery 一起工作是一个额外的好处。
9 回答
这是一个完整的函数(取自PHPJS):
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
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]
用这个
unescape(str);
我不是一个伟大的 JS 程序员,尝试了所有,这太棒了!
//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 的 decodeURIComponent 一起使用,而无需替换 + 字符。
这是我使用的:
在 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.com 上使用encodeURIComponent()
直接.
良好的代码结果:
thing%2athing%20thing%21
错误代码导致encodeURIComponent()
:
thing*thing%20thing!