1

How would I use JavaScript to look for a specific domain name and then return true if its the one I am looking for, or false if it is not the URL that I am looking for. In my example a user types a URL in an input box, JavaScript checks if it is a specific domain such as https://example.com and then redirects the user to that page. If they type another URL without the https://example.com, JavaScript will return false and show an error message. If a user types the URL https://example.com/join/1234 I just wish to check the main domain. The code I have so far is below. I have tried using regex butI dont know how I can make it only check the domain name -> 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",
        });
    }
1
  • Please provide the code of the isDomainURL method and report what the problem you are facing. Commented May 6, 2020 at 17:39

1 Answer 1

2

I would recommend the usage of a URL object for this purpose.

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

console.log(url.host);   

It's way simpler that usage of regexp.

Please keep in mind that relative URLs are also acceptable, thus, I would recommend checking if the protocol is a part of the string.

Sign up to request clarification or add additional context in comments.

3 Comments

How would I check to see if url.host is example.com? Then return true or false?
if (url.host === 'example.com') { ... }
I think it is worth mentioning that there is another property on an URL instance, hostname. Let's assume localhost:3000 as URL. host is equal to localhost:3000 and hostname is equal to localhost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.