我的正则表达式很差,所以希望能在这里得到一些帮助。我有一个url,它有一个查询字符串参数。该参数依次是具有其自身的qs参数的url。例如:我的url是这样的
现在,当我使用任何函数来提取整个查询字符串参数时,不知何故只得到了第一个参数。
我期望的是: /en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true::
,但我得到的是: /en-us/products-overview/find-product/home/kitchen/2980?source=google
请注意,缺少其他两个参数(isadvertisement和organic)。
我的函数是
function getUrlParameter(name) {
var url = 'http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true';
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
JsFiddle here
我尝试了SO中的其他链接来提取QS参数。它们似乎都不能处理这种情况。
发布于 2018-08-21 05:40:53
url中的&符号将被视为顶级参数分隔符。如果它们本身是参数的一部分,则需要对它们进行转义。转义后的url将类似于http://myurl.com/somepage?ref=%2Fen-us%2Fproducts-overview%2Ffind-product%2Fhome%2Fkitchen%2F2980%3Fsource%3Dgoogle%26isadvertisement%3Dfalse%26organic%3Dtrue。如何对url进行编码取决于它的来源。JS提供了encodeURIComponent()
函数。
然后,您可以使用decodeURIComponent()
将其解码回预期的url。问题来自于具有嵌套的查询参数。
不过,要获得一般的查询参数,使用URL的内置解决方案可能如下所示:
var url=new URL('...');
for (var e of url.searchParams.entries()){
console.log(e);
}
https://stackoverflow.com/questions/51938603
复制相似问题