这应该是一个简单的任务,但我似乎无法找到解决的办法。
我有被穿过的这样一个查询字符串参数基本字符串: 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
function doesn't convert +
to space, 但 there are some things worth to realize here:
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。
下面的代码将解码,让您以对象的形式PARAMS
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"));
}