如何知道一个 url 在 javascript 中是否有参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26483886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to know if a url has parameters in javascript
提问by Juanjo
I want to check if a url has parameters or it doesn't, so I know how to append the following parameters(with ? or &). In Javascript
我想检查一个 url 是否有参数,所以我知道如何附加以下参数(使用 ? 或 &)。在 JavaScript 中
Thanks in advance
提前致谢
Edit: With this solution it works perfectly:
编辑:使用此解决方案,它可以完美运行:
myURL.indexOf("?") > -1
回答by Andy
Split the string, and if the resulting array is greater than one and the second element isn't an empty string, at least one parameter has been found.
拆分字符串,如果结果数组大于一且第二个元素不是空字符串,则至少找到了一个参数。
var arr = url.split('?');
if (url.length > 1 && arr[1] !== '') {
console.log('params found');
}
Note this method will also work for the following edge-case:
请注意,此方法也适用于以下边缘情况:
http://myurl.net/?
You could also match the url against a regex:
您还可以将 url 与正则表达式匹配:
if (url.match(/\?./)) {
console.log(url.split('?'))
}
回答by Kiran Maniya
Just go through the code snippet, First, get the complete URL and then check for ?using includes()method.includes()can be used to find out substring exists or not and using locationwe can obtain full URL.
只需通过代码片段,首先,获取完整的 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');
}
回答by ummahusla
You can try this:
你可以试试这个:
if (url.contains('?')) {} else {}

