156

最好的 JavaScript URL 解码实用程序是什么?编码也很好,与 jQuery 一起工作是一个额外的好处。

4

9 回答 9

239

这是一个完整的函数(取自PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
于 2010-12-16T08:03:01.027 回答
220

我也使用了encodeURIComponent()decodeURIComponent()

于 2010-11-27T17:34:10.433 回答
9
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]
于 2011-04-19T18:12:58.647 回答
9

用这个

unescape(str);

我不是一个伟大的 JS 程序员,尝试了所有,这太棒了!

于 2013-02-13T12:51:09.507 回答
3
//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));
于 2013-01-11T06:40:41.707 回答
2

如果您负责使用 urlencode 在 PHP 中对数据进行编码,则 PHP 的 rawurlencode 可以与 JavaScript 的 decodeURIComponent 一起使用,而无需替换 + 字符。

于 2014-04-29T16:39:19.433 回答
0

这是我使用的:

在 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

于 2015-07-15T13:03:36.747 回答
0

var uri = "my test.asp?name=ståle&car=saab";
console.log(encodeURI(uri));

于 2018-08-04T06:09:19.193 回答
0

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!

于 2020-05-31T20:34:53.000 回答