A URL – or Uniform Resource Locator – is text used to identify resources like web pages, images, and videos on the internet. We commonly refer to URLs as website addresses, and they're used for file transfer, emails, and other applications. URLs consist of multiple parts – protocol, domain name, and so on – that tell the browser how and where to retrieve the resource. In JavaScript, you may need to use a URL in the anchor tags or buttons to link the user to another webpage. This URL string must be verified to make sure it's a valid URL in such situations. This tutorial will teach you some ways to check if a JavaScript string is a valid URL. To learn how to get the current URL in JavaScript, you can read this article on How to Get the Current URL in JavaScript. Regular expressions (regex) are patterns that match character combinations in a JavaScript string. In JavaScript, regular expressions are also known as objects that provide different methods to perform various operations. You can construct a regular expression in two ways: Note: It is appropriate to use the regular expression method when you just want to check if a string is a valid URL and don't want any other additional objects created. Let's learn how these two methods work. In a regular expression literal, the pattern is enclosed between the slashes, as you'll see below. The pattern includes the validation of parts needed in the
How to use a regular expression constructorTo create a regular expression using the construction method, use the 6 constructor and pass the pattern as a parameter.
To demonstrate how to validate if a string is a 3, let's create a method that will validate a JavaScript 8 using the regular expression constructor and return 9 or 0 based on the matched pattern.
How to use regex to validate a URL stringThe code below demonstrates how to validate different URL strings using the above method:
How to Check if a String is a Valid URL using URL ConstructorYou can use the URLConstructor to check if a string is a valid URL. URLConstructor ( 1) returns a newly created URL object defined by the URL parameters.A JavaScript 2 exception is thrown if the given URL is not valid.Note: It is appropriate to use this method when you want to construct a URL object in your program for further uses. URL Constructor SyntaxThe following syntax explains how to create a URL Object with a JavaScript String.
Where,
Example of URL Constructor methodTo demonstrate how the URL constructor method works, let's create a lambda function in JavaScript to construct a new URL with the passed string.
How to use the const isValidUrl = urlString=> { var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol '((([a-z\\d]([a-z\\d-]*[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); } 8 methodLet's invoke the 8 method for different string types and see the results.
In the first three cases, you can see that an invalid URL string is passed. As a result, URL object creation fails with a 2 and 7 is returned.In the last two cases, valid URL string is passed. So a 3 object is created successfully, and 9 is returned, confirming the proper URL.Let's see one more example to validate a specific URL part. In this example, you are validating a specific protocol in the URL. The URL must contain the 4 or 4 protocol.
Example of how to validate part of a URLLet's invoke the 8 method for different string types and protocols and see the results.
In the first case, the URL string (tcp://www.jsowl.com) is valid, but it doesn't contain a specific protocol ( 7/ 8). So it returns false.In the second case, the URL string https://www.jsowl.com is valid and contains the specific protocol. So it returns true. How to Check if a String is a Valid URL Using an Input ElementHTML supports an input element with type 3, specifically for representing URL values.The 0 element's 1 attribute containing the string is automatically validated by matching the URL syntax (either has an empty or properly formed URL) before the form can be submitted. 2 method is used to check if a string in 0 element’s value attribute is 3. The 5 method returns 5 if the value is a proper URL and 7 if the input is not a proper URL.Let's create a method which creates an input element type 3 and validates the input using the 9 method.
Now let's use this method and validate different strings to see if they are valid URLs. 0This is how you can use the input type method to check if a string is a valid URL. How to Check if a String is a Valid URL Using the Anchor Tag MethodThis section teaches you how to use the HTMLAnchorElement to check whether a JavaScript string is a URL. Note: It is appropriate to use this method when you want to assign a URL to the 0 tag of your webpage and ensure that the URL string is valid and gets assigned to the 0 tag properly.The 2 interface represents hyperlink elements. It provides special properties and methods for manipulating the layout and presentation of such elements. It is also called an anchor tag.You can assign a URL to an anchor tag using the 3 attribute. While assigning,
Once the URL is assigned, you can extract a specific part of the URL using the attributes explained below. HTMLAnchorElement atributeusage 4a string representing hostname and port 5a string representing hostname 3a string containing a valid URL 7returns a string containing the origin, its schema, domain name and port 8a string representing the port if specified 9a string representing the protocol including the trailing(' 0') 1a string containing the path URL from initial (/) and not including the query stringNow, let's see how to check if the assigned string was a proper URL. If it was a proper URL, it would be assigned to the anchor tag. Else, the current browser location will be assigned to the anchor tag. So to check if it was a proper URL, you can check if the anchor tag’s 4 is NOT equal to the current location using the statement 3.Let's look at the code. We create a lambda function and assign it to the constant 4 in the code below.The function creates an anchor tag element and assigns the URL string to the anchor tag. After that, it checks if the 4 attribute of the element is 6 or not defined.If it is not null, it checks whether the 4 attribute is NOT equal to the current browser URL and returns 9 when it is not equal.This is because if the passed URL was valid, then the anchor tag will have the URL value. But if the passed URL was invalid, the anchor tag will have the current browser location. In this case, the lambda function returns 0. 1The below code snippets invoke the lambda function 0 with different inputs and print the output accordingly in the console. 2This tutorial is available in this JSFiddle. ConclusionIn this article, you've learned how to check if a JavaScript string is a 3 using different methods and when it is appropriate to use each method.If you liked this article, feel free to share it. You can check out my other tutorials on my blog, JS Owl. ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT ADVERTISEMENT AWS Solutions Architect and Full-time Technical writer at stackvidhya.com and jsowl.com. If you read this far, tweet to the author to show them you care. Tweet a thanks Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started How to get the domain name from URL in JavaScript?Follow the syntax below to get the hostname. var url = new URL("www.sample.com"); var hostname = url. hostname; Here we access the hostname property from the URL directly.
How do I extract a domain name from a URL?In the first cell of the "Domain" column (B2), enter the formula to extract a domain name:. Extract the domain with www. if it is present in a URL: =MID(A2,FIND(":",A2,4)+3,FIND("/",A2,9)-FIND(":",A2,4)-3). Omit www. and get a pure domain name: =IF(ISERROR(FIND("//www.",. Can I use regex in URL?URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.
How to split domain name in JavaScript?var newURL="http://www.example.com/index.html/homePage/aboutus/"; console. log(newURL); var splitURL=newURL. toString(). split("/"); console.
|