这应该是一项简单的任务,但我似乎找不到解决方案。
我有被穿过的这样一个查询字符串参数基本字符串: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 函数确实不会将 + 转换为空格。所以你必须使用替换功能替换 + 。
理想情况下,以下解决方案有效。
var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));
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') );
加号未编码/解码。要查看 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"));
}