JavaScript URL 解码功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4292914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:47:34  来源:igfitidea点击:

JavaScript URL Decode function

javascriptjqueryurlencodeurldecode

提问by at.

What's the best JavaScript URL decode utility? Encoding would be nice too and working well with jQuery is an added bonus.

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

回答by anshuman

Here is a complete function (taken from PHPJS):

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

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

回答by Etienne Dupuis

decodeURIComponent(mystring);

you can get passed parameters by using this bit of code:

您可以使用以下代码获取传递的参数:

//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;
}

Or this one-liner to get the parameters:

或者这个单行获取参数:

location.search.split("your_parameter=")[1]

回答by nithinreddy

Use this

用这个

unescape(str);

I'm not a great JS programmer, tried all, and this worked awesome!

我不是一个出色的 JS 程序员,尝试了所有方法,效果非常好!

回答by Irfan M

//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));

回答by Brent Self

If you are responsible for encoding the data in PHP using urlencode, PHP's rawurlencode works with JavaScript's decodeURIComponent without needing to replace the + character.

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

回答by user3572058

Here's what I used:

这是我使用的:

In JavaScript:

在 JavaScript 中:

var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);

var decoded_url = decodeURIComponent(encoded_url);

In PHP:

在 PHP 中:

$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);

$decoded_url = url_decode($encoded_url);

You can also try it online here: http://www.mynewsfeed.x10.mx/articles/index.php?id=17

您也可以在这里在线试用:http: //www.mynewsfeed.x10.mx/articles/index.php?id=17

回答by methodpool.io

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