A URL – or Uniform Resource Locator – is text used to identify resources like web pages, images, and videos on the internet.
We often refer to URLs as web addresses, and they are used to transfer files, emails, and other applications.
URLs contain multiple components – protocol, domain name, etc. – that tell the browser how and where to find the service.
In JavaScript, you may need to use the URL in bankmarks or buttons to connect a user to another webpage. This series of URLs must be verified to ensure that the URL is valid in such cases.
This tutorial will teach you some ways to check if a JavaScript character unit is a valid URL.
To learn how to get the current URL in JavaScript, you can read the article How to Get the Current URL in JavaScript.
How to Check if String is a valid URL using Regex
Common expressions (regex) are patterns similar to letter combinations in a JavaScript character unit. In JavaScript, standard add-ons are also known as providing different ways of performing various tasks.
You can create a common saying in two ways:
- Using standard add-ons
- Normal add-on builders are used
Note: It is advisable to use the standard way of saying if you want to check if a string is a valid URL and do not want additional features created.
Let’s learn how these two methods work.
How to use Regular expressions
In normal verbal expression, the pattern is enclosed between slashes, as you will see below.
Pattern includes verification of required components in the URL. For example, protocol, https, //, and so on.
const urlPattern = /(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!-\/]))?/;
How to use a RegExp constructor
To create a common expression using the construct method, use the RegExp () constructor and pass the pattern as a parameter.
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!-\/]))?');
In order to specify a verification method if a character unit is a URL, let’s create a method that will verify the JavaScript String using the standard speech element and return true or false based on the matching pattern.
const isValidUrl = urlString=> {
var urlPattern = new RegExp('^(https?:\/\/)?'+ // validate protocol
'(((a-z\d)\.)+[a-z]{2,}|'+ // validate domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // validate OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%.~+])'+ // validate port and path
'(\?[;&a-z\d%.~+=-])?'+ // validate query string
'(\#[-a-z\d_]*)?$','i'); // validate fragment locator
return !!urlPattern.test(urlString);
}
How to use regex to verify a unit of URLs
The code below shows how to validate different URL units of a URL using the method above:
var url = "invalidURL";
console.log(isValidUrl(url)); //false
var url = "htt//coding"; //false
console.log(isValidUrl(url));
var url = "www.codingsutra.in"; //true
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in"; //true
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in/why-you-should-learn-javascript/";
console.log(isValidUrl(url)); //true
How to Check String is a valid URL using URL Constructor
You can use URLConstructor to check if a string is a valid URL.
URLConstructor (new URL (url)) returns the newly created URL object defined by the URL parameters.
A JavaScript TypeError variant is thrown when the given URL is invalid.
Note: It is advisable to use this method if you want to create a URL object in your system to use it.
URL Constructor Syntax
The following syntax explains how to create an Object URL with a JavaScript Thread.
new URL(url);
new URL(url, base);
There,
- url is a unit of characters or any object with a stringifier representing a complete or related URL. If the URL is a complete URL, the base will be ignored. If the URL is a related URL, a base is required.
- base (optional) character unit representing the primary URL. Must be forwarded if the URL is related. Default for unspecified when ignored.
An example of a URL constructor
To illustrate how a URL constructor works, let’s create a lambda function in JavaScript to create a new URL in the previous series.
- When a string is a valid URL, a URL object is created, and the truth is restored
- If the Series is not a valid URL, a separate Tyeperror release, and the false one is returned
const isValidUrl = urlString=> {
try {
return Boolean(new URL(urlString));
}
catch(e){
return false;
}
}
How to use the isValidURL() method
Let’s take a look at the isValidURL() method for different types of cables and see the results.
var url = "invalidURL";
console.log(isValidUrl(url)); //false
var url = "htt//coding"; //false
console.log(isValidUrl(url));
var url = "www.codingsutra.in"; //true
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in"; //true
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in/why-you-should-learn-javascript/";
console.log(isValidUrl(url)); //true
In the first three cases, you can see that an invalid URL series has been transferred. As a result, the URL object creation fails with TypeError and false returns.
In the last two cases, a valid URL series is transferred. So the URL object was successfully created, and the Truth is restored, which guarantees the correct URL.
Let’s look at another example of verifying a specific part of a URL.
In this example, you verify a specific protocol at the URL. URL must contain an http or https protocol.
const isValidUrl = urlString=> {
let url;
try {
url =new URL(urlString);
}
catch(e){
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
An example of how to verify a URL component
Let’s ask for isValidURL () method for different types of cables and protocols and see the results.
var url = "tcp://www.codingsutra.in"; //fasle
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in"; //true
console.log(isValidUrl(url));
In the first case, the URL unit (tcp: //www.codingsutra.in) is valid, but does not contain a specific protocol (HTTP / HTTPS). So it comes back false.
In the second case, the URL character unit https://www.codingsutra.in is valid and contains a specific protocol. So it returns to the truth.
How to check that String is a valid URL using the input element
HTML supports input url type input, which represents the URL values.
The attribute value of an element containing a character unit is automatically verified by matching the syntax of the URL (either with an empty or well-built URL) before submitting the form.
The HTMLInputElement.checkValidity() method is used to check if a element value string is a URL. The checkvalidity() method returns the truth if the value is the correct URL and is false if the input is not the correct URL.
Let’s create a path that creates the URL type of the input type and verifies the input using the checkValidity() method.
const isValidUrl = urlString =>{
var inputElement = document.createElement('input');
inputElement.type = 'url';
inputElement.value = urlString;
if (!inputElement.checkValidity()) {
return false;
} else {
return true;
}
}
Now let’s use this method and verify the different character units to see if they are valid URLs.
var url = "invalidURL";
console.log(isValidUrl(url)); //false
var url = "htt//coding"; //false
console.log(isValidUrl(url));
var url = "www.codingsutra.in"; //false
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in"; //true
console.log(isValidUrl(url));
var url = "https://www.codingsutra.in/why-you-should-learn-javascript/";
console.log(isValidUrl(url)); //true
This is how you can use the input method method to check if a string is a valid URL.
How to Check String is a valid URL using the Anchor Tag Method
This section teaches you how to use HTMLAnchorElement to check if a JavaScript series is a URL.
Note: It is appropriate to use this method if you want to assign a URL to the anchor tag of your webpage and ensure that the URL unit is valid and assigned to the anchor tag correctly.
The HTMLAnchorElement interface represents link features. Provides specialized structures and mechanisms to counteract the design and presentation of such materials. Also called anchor tag.
You can assign a URL to an anchor using the href attribute. While sharing,
- When a character unit of a valid URL is transferred, it is given an anchor tag
- If an invalid URL is passed, the current browser location is given to the anchor tag
- By default, the anchor tag will have an empty URL (“”)
Once the URL is assigned, you can extract a specific portion of the URL using the attributes described below.
HTMLANCHORELEMENT ATTRIBUTE | USAGE |
---|---|
host | a string representing hostname and port |
hostname | a string representing hostname |
href | a string containing a valid URL |
origin | returns a string containing the origin, its schema, domain name and port |
port | a string representing the port if specified |
protocol | a string representing the protocol including the trailing(‘: ‘) |
pathname | a string containing the path URL from initial (/) and not including the query string |
Now, let’s see how we can determine if the assigned character unit was the correct URL.
If it was a valid URL, it would be given an anchor tag. If not, the current browser location will be assigned to the anchor.
So to check if it was the correct URL, you can check if the anchor tag is NOT compatible with the current location using the statement a.host! = Window.location.host.
Let’s look at the code.
We create a lambda function and provide it with isValidUrl unchanged in the code below.
The function creates an anchor marker feature and assigns a unit of URLs to the anchor tag. Next, it checks whether the host identifier of the item is empty or unspecified.
If it is not in vain, it checks that the host attribute does NOT match the current browser URL and returns the truth if it does not match.
This is because if the forwarded URL was valid, the anchor tag will have the URL value. But if the forwarded URL was invalid, the anchor tag will replace the current browser. In this case, the function of the lambda restores falsehood.
const isValidUrl = urlString =>{
var a = document.createElement('a');
a.href = urlString;
return (a.host && a.host != window.location.host);}
The captions below call the lambda functionValidUrl () in a separate input and print the output accordingly to the console.
var url = "invalidURL";
console.log("1.AnchorTag: " +isValidUrl(url)); //false
var url = "htt//coding";
console.log("22.AnchorTag: "+isValidUrl(url)); //false
var url = "www.codingsutra.in";
console.log("3.AnchorTag: " +isValidUrl(url)); //false
var url = "https://www.codingsutra.in";
console.log("4.AnchorTag: " +isValidUrl(url)); //true
var url = "https://www.codingsutra.in/why-you-should-learn-javascript/";
console.log("5.AnchorTag: " +isValidUrl(url)); //true
Conclusion
In this article, you will learn how to determine if a JavaScript character is a URL using different methods and when to use each method.
If you liked this article, feel free to share it.
Don’t Miss This: