使用 JavaScript 解码 URL 参数

IT技术 javascript html forms decoding url-parameters
2021-02-28 01:45:34

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

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

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

5个回答

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

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

var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));
+ 不是有效的空间 uri 编码。一些网站只是选择更换空间与网址+-_等,因为它更具有可读性,但它不是标准化
2021-04-28 01:45:34
这是更好的答案。encodeURIComponent可能会选择不将空格编码为+,更喜欢%20,但 URI 可能来自其他地方,并且+对于由于未知原因 JSdecodeURIComponent决定忽略的空格是完全有效的编码
2021-04-30 01:45:34
就像已经指出的那样,decodeURI函数不会转换+为空间,这里有一些值得实现的事情:
  • decodeURI是指用于整个URI,即不解码分隔喜欢?&=+,等。
  • decodeURIComponent应该使用解码参数
    (值得一看:decodeURIComponent 和 decodeURI 有什么区别?
  • 您尝试解码的字符串实际上可能包含+编码为%2B,因此您不应该+在转换后替换,因为您可能会丢失+您实际想要的符号,例如something?num=%2B632+905+123+4567应该成为:
    something?num=+632 905 123 4567
    因为您可能要提取数字:+632 905 123 4567

所以正确的做法是:

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

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

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

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

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

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

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

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

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

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

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