我想检查一个URL是否有参数,以便我知道如何添加下列参数(用?或&)。在Javascript中。
提前感谢。
编辑: 使用这个解决方案,它完美地工作:
myURL.indexOf("?") > -1
我想检查一个URL是否有参数,以便我知道如何添加下列参数(用?或&)。在Javascript中。
提前感谢。
编辑: 使用这个解决方案,它完美地工作:
myURL.indexOf("?") > -1
将字符串分割,如果结果数组长度大于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('?'))
}
请看这段代码片段,首先获取完整的 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');
}
if (url.contains('?')) {} else {}
contains
是一项试验性技术,属于Harmony(ECMAScript 6)提案的一部分。” - Andyurl.includes(word);
参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - Avatarvar url = YourURL;
if(url.includes('?')) {} else {}
如果URL中存在"?",则url.includes('?')将返回true。
if (window.location.search) {
console.log ("This page was called with paramters")
} else {
console.log ("No Parameters found")
}