使用 JavaScript 解码 URL 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12042592/
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 06:58:03  来源:igfitidea点击:

Decoding URL parameters with JavaScript

javascripthtmlformsdecodingurl-parameters

提问by user852367

This should be a simple task, but I can't seem to find a solution.

这应该是一项简单的任务,但我似乎找不到解决方案。

I have a basic string that is being passed through as a query string parameter like this one: This+is+a+message+with+spaces. I would like to decode that parameter using JavaScript to This is a message with spaces, but I cannot seem to get it to decode.

我有被穿过的这样一个查询字符串参数基本字符串:This+is+a+message+with+spaces。我想使用 JavaScript 将该参数解码为This is a message with spaces,但我似乎无法对其进行解码。

I've tried decodeURI('This+is+a+message+with+spaces')but the result still contains the +signs.

我试过了,decodeURI('This+is+a+message+with+spaces')但结果仍然包含这些+迹象。

回答by Supriti Panda

Yes it is true that decodeURIComponent function doesn't convert + to space. So you have to replace the + using replace function.

是的,decodeURIComponent 函数确实不会将 + 转换为空格。所以你必须使用替换功能替换 + 。

Ideally the below solution works.

理想情况下,以下解决方案有效。

var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));

回答by LihO

就像已经指出的那样,decodeURIdecodeURI函数不会转换++为空间,but这里有一些值得意识到的事情:
  • decodeURIis meant to be used for whole URI, i.e. it doesn't decode separators like ?, &, =, +, etc.
  • for decoding parameters decodeURIComponentshould be used
    (worth to have a look at: What is the difference between decodeURIComponent and decodeURI?)
  • string that you are trying to decode might actually contain +encoded as %2B, thus you should not replace +after the conversion since you might lost +signs that you actually want there, e.g. something?num=%2B632+905+123+4567should become:
    something?num=+632 905 123 4567
    since you are probably going to extract the number: +632 905 123 4567
  • decodeURI是指用于整个URI,即不解码分隔喜欢?&=+,等。
  • decodeURIComponent应该使用解码参数
    (值得一看:decodeURIComponent 和 decodeURI 有什么区别?
  • 您尝试解码的字符串实际上可能包含+编码为%2B,因此您不应该+在转换后替换,因为您可能会丢失+您实际想要的符号,例如something?num=%2B632+905+123+4567应该成为:
    something?num=+632 905 123 4567
    因为您可能要提取数字:+632 905 123 4567

So the correct way to do this is:

所以正确的做法是:

var str = 'something?num=%2B632+905+123+4567';
decodeURIComponent( str.replace(/\+/g, '%20') );

回答by davidbuzatto

The plus sign is not encoded/decoded. To see the decode function working, you need to pass a encoded URI first. Take a look:

加号未编码/解码。要查看 decode 函数的工作情况,您需要先传递一个编码的 URI。看一看:

encodeURI( "http://www.foo.com/bar?foo=foo bar jar" )

Will generate: http://www.foo.com/bar?foo=foo%20bar%20jar, i.e., the encoded URI.

将生成:http://www.foo.com/bar?foo=foo%20bar%20jar,即编码后的 URI。

decodeURI( "http://www.foo.com/bar?foo=foo%20bar%20jar" )

Will generate: http://www.foo.com/bar?foo=foo bar jar, i.e., the decoded URI.

将生成:http://www.foo.com/bar?foo=foo bar jar,即解码后的 URI。

回答by Varsha Jadhav

The below code will decode and gives you the params in form of objects

下面的代码将解码并以对象的形式为您提供参数

export function getParamsFromUrl(url) {
    url = decodeURI(url);
    if (typeof url === 'string') {
        let params = url.split('?');
        let eachParamsArr = params[1].split('&');
        let obj = {};
        if (eachParamsArr && eachParamsArr.length) {
            eachParamsArr.map(param => {
                let keyValuePair = param.split('=')
                let key = keyValuePair[0];
                let value = keyValuePair[1];
                obj[key] = value;
            })
        }
        return obj;
    }
}

回答by Harvey

I created my own string methods to support the needed encoding/decoding. These methods will handle the + encoding and decoding properly, allowing you to have plusses (+) in your string and still have the original spaces be encoded as +'s.

我创建了自己的字符串方法来支持所需的编码/解码。这些方法将正确处理 + 编码和解码,允许您在字符串中有加号 (+) 并且仍然将原始空格编码为 +。

String.prototype.plusEncode = function() {
    return encodeURIComponent(this).replace(/\%20/gm,"+");
}

String.prototype.plusDecode = function() {
    return decodeURIComponent(this.replace(/\+/gm,"%20"));
}