【问题标题】:JavaScript - How to check for URL with specific domain name?JavaScript - 如何检查具有特定域名的 URL?
【发布时间】:2020-08-21 18:57:06
【问题描述】:

我将如何使用 JavaScript 来查找特定的域名,如果它是我正在寻找的域名,则返回 true,如果它不是我正在寻找的 URL,则返回 false。在我的示例中,用户在输入框中键入 URL,JavaScript 检查它是否是特定域,例如 https://example.com,然后将用户重定向到该页面。如果他们键入另一个没有https://example.com 的 URL,JavaScript 将返回 false 并显示错误消息。如果用户键入 URL https://example.com/join/1234 我只想检查主域。我到目前为止的代码如下。我曾尝试使用正则表达式,但我不知道如何让它只检查域名 -> https://example.com

 <div class="col-md-12 col-lg-5"><button class="btn btn-primary btn-lg" id = "start-call" data-aos="zoom-in" data-aos-duration="900" data-aos-delay="2000" type="button" style="margin: 160px;width: 135px;" onclick = "goToCall()" >Start Call</button></div>


 function isDomainURL(str){
  regexp =  /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
    if (regexp.test(str)){

    return true;

    }else{

    return false:

    }

 }

 if (isDomainURL(document.getElementById('input-01').value) == true)
    {
        window.location = document.getElementById('input-01').value;
    }
    else
    {
        swal({
            title: "Invalid URL",
            text: "Thats was an invalid DropCall URL.",
            icon: "error",
        });
    }

【问题讨论】:

  • 请提供isDomainURL方法的代码并报告您遇到的问题。

标签: javascript url redirect


【解决方案1】:

我建议为此使用 URL 对象。

const url = new URL('https://example.com/my-path');

console.log(url.host);   

使用正则表达式更简单。

请记住,相对 URL 也是可以接受的,因此,我建议检查协议是否是字符串的一部分。

【讨论】:

  • 如何检查 url.host 是否为 example.com?然后返回true还是false?
  • if (url.host === 'example.com') { ... }
猜你喜欢
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2012-03-13
  • 2010-09-13
相关资源
最近更新 更多