我想检查一个url是否有参数或者它没有,所以我知道如何附加以下参数(带?或&).在Javascript中
提前致谢
编辑:使用此解决方案,它完美地工作:
myURL.indexOf("?") > -1
Run Code Online (Sandbox Code Playgroud)
拆分字符串,如果结果数组大于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.contains('?')) {} else {}
Run Code Online (Sandbox Code Playgroud)
只需通过代码片段,首先,获取完整的 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)