簡體   English   中英

JavaScript - 如何檢查具有特定域名的 URL?

[英]JavaScript - How to check for URL with specific domain name?

我將如何使用 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",
        });
    }

為此,我建議使用 URL 對象。

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

使用正則表達式要簡單得多。

請記住,相對 URL 也是可以接受的,因此,我建議檢查協議是否是字符串的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM