这看起来是一个简单的任务,但我似乎找不到解决方法。
我有一个基本字符串作为查询字符串参数传递,就像这个:This+is+a+message+with+spaces
。我想使用JavaScript对该参数进行解码,使其变成This is a message with spaces
,但我似乎无法对其进行解码。
我已尝试过decodeURI('This+is+a+message+with+spaces')
,但结果仍然包含+
符号。
这看起来是一个简单的任务,但我似乎找不到解决方法。
我有一个基本字符串作为查询字符串参数传递,就像这个:This+is+a+message+with+spaces
。我想使用JavaScript对该参数进行解码,使其变成This is a message with spaces
,但我似乎无法对其进行解码。
我已尝试过decodeURI('This+is+a+message+with+spaces')
,但结果仍然包含+
符号。
是的,decodeURIComponent函数不会将加号转换为空格。因此,您需要使用replace函数来替换加号。
理想情况下,以下解决方案可行。
var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));
encodeURIComponent
可能会选择不将空格编码为 +
,而更喜欢 %20
,但 URI 可能来自其他地方,并且 +
是一个完全有效的空格编码,JS 的 decodeURIComponent
函数由于未知原因选择忽略它。 - abligh+
、-
、_
等字符替换 URL 中的空格,因为这样更易读,但这并不是标准化的做法。decodeURI
函数不会将+
转换为空格,但是这里有一些值得注意的事情:
decodeURI
旨在用于整个URI,即它不会解码分隔符,如?
、&
、=
、+
等。decodeURIComponent
%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') );
加号不被编码/解码。为了看到解码函数的工作,您需要先传递一个已编码的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"));
}
decodeURIComponent('This+is+a+message+with+spaces')
仍然返回This+is+a+message+with+spaces
。encodeURIComponent('This+is+a+message+with+spaces')
返回This%2Bis%2Ba%2Bmessage%2Bwith%2Bspaces
。我一定漏掉了什么,因为我没有看到这如何解决我的问题。 - user852367