如何在JavaScript中判断URL是否有参数

17

我想检查一个URL是否有参数,以便我知道如何添加下列参数(用?或&)。在Javascript中。

提前感谢。

编辑: 使用这个解决方案,它完美地工作:

myURL.indexOf("?") > -1

1
只需通过“?”拆分Url并获取拆分数组的长度,如果长度为1,则该url没有参数,如果长度大于1,则存在参数。 - Amy
可能是重复的问题:如何在JavaScript中获取查询字符串值? - Lee Taylor
5个回答

11

将字符串分割,如果结果数组长度大于1且第二个元素不是空字符串,则至少找到了一个参数。

var arr = url.split('?');
if (arr.length > 1 && arr[1] !== '') {
  console.log('params found');
}

请注意,这种方法也适用于以下特殊情况:

http://myurl.net/?

您也可以使用正则表达式匹配URL:

if (url.match(/\?./)) {
  console.log(url.split('?'))
}

4
我不得不将条件从 if (url.length...) 改为 if (arr.length...),这对我很有效。 - danielarend

9

请看这段代码片段,首先获取完整的 URL,然后使用 includes() 方法检查是否存在 ?。可以使用 includes() 来查找子字符串是否存在,使用 location 可以获得完整的 URL。

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

let url = window.location.href;
if(url.includes('?')){
  console.log('Parameterised URL');
}else{
  console.log('No Parameters in URL');
}


5
你可以尝试这个方法:
if (url.contains('?')) {} else {}

2
那是因为“contains是一项试验性技术,属于Harmony(ECMAScript 6)提案的一部分。” - Andy
现在它已经成为标准了,但是 url.includes(word); 参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - Avatar

2
你也可以尝试这个方法。
var url = YourURL;
if(url.includes('?')) {} else {}

如果URL中存在"?",则url.includes('?')将返回true。


1
如果您正在页面上,并且想要检查页面是否带有参数调用:
if (window.location.search) {
    console.log ("This page was called with paramters")
  } else {
    console.log ("No Parameters found")
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接