如何知道url是否在javascript中有参数

Jua*_*njo 6 javascript url

我想检查一个url是否有参数或者它没有,所以我知道如何附加以下参数(带?或&).在Javascript中

提前致谢

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

myURL.indexOf("?") > -1
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 6

拆分字符串,如果结果数组大于1而第二个元素不是空字符串,则至少找到一个参数.

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

请注意,此方法也适用于以下边缘情况:

http://myurl.net/?
Run Code Online (Sandbox Code Playgroud)

您还可以将网址与正则表达式进行匹配:

if (url.match(/\?./)) {
  console.log(url.split('?'))
}
Run Code Online (Sandbox Code Playgroud)

  • 我不得不将条件 if (url.length...) 更改为 if (arr.length...) 并且它对我来说很好用 (3认同)

umm*_*sla 5

你可以试试这个:

if (url.contains('?')) {} else {}
Run Code Online (Sandbox Code Playgroud)

  • 这是因为 ["`contains` 是一项实验性技术,是 Harmony (ECMAScript 6) 提案的一部分。"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String /包含) (2认同)

Kir*_*iya 5

只需通过代码片段,首先,获取完整的 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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)