Reputation: 45
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",
});
}
Upvotes: 1
Views: 2429
Reputation: 4811
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.
Upvotes: 2