【问题标题】:How to know if a url has parameters in javascript如何知道一个url是否有javascript中的参数
【发布时间】:2014-10-21 09:58:07
【问题描述】:

我想检查一个 url 是否有参数,所以我知道如何附加以下参数(使用 ? 或 &)。在Javascript中

提前致谢

编辑: 使用此解决方案,它可以完美运行:

myURL.indexOf("?") > -1

【问题讨论】:

标签: javascript url


【解决方案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('?'))
}

【讨论】:

  • 我不得不将条件 if (url.length...) 更改为 if (arr.length...) 并且对我来说效果很好
【解决方案2】:

只需通过代码sn-p,首先,获取完整的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');
}

【讨论】:

    【解决方案3】:

    你可以试试这个:

    if (url.contains('?')) {} else {}
    
    【解决方案4】:

    你也可以试试这个。

    var url = YourURL;
    if(url.includes('?')) {} else {}
    

    url.includes('?') 如果 ?存在于 URL 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多