This article discusses checking if a string is a valid URL in javascript using different methods and examples for illustration.
Table of Contents:
Javascript check if string is URL: regex
This section will look into the javascript function, which checks if the string is a valid URL. The function checks for a pattern in the string, and if the pattern matches, then returns true. Else returns false. Observe the below pattern.
Javascript function to check if the string is a valid URL
The pattern in this function will check for a valid URL skeleton such as the URL protocol, domain name, ip address etc.
Frequently Asked:
function isValidUrl(_string) { const matchpattern = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm; return matchpattern.test(_string); }
OR
function isValidUrl(_string){ const matchPattern = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/; return matchPattern.test(_string); }
Test with Example_1:
Check if the string “A Random String” is a valid URL.
let _string1 = "A Random String" isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")
Output:-
URL is Invalid
Test with Example_2:
Check if string “https://www.managementbliss.com” is a valid URL
let _string1 = "https://www.managementbliss.com" isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")
Output:-
URL is Valid
Javascript check if string is URL using URL Interface
In this section, we will use the URL Interface to check if the string is a valid URL or not.
Javascript function to check if the string is a valid URL
The below function checks if the string is a valid URL. A URL constructor is used to create a new URL object and then check if the url_object.protocol equals http or https. The function returns true if the url_object.protocol is either https or http. Else returns false.
function isValidUrl(_string) { let url_string; try { url_string = new URL(_string); } catch (_) { return false; } return url_string.protocol === "http:" || url_string.protocol === "https:" ; }
Test with Example_1:
Check if the string “A Random String” is a valid URL.
let _string1 = "A Random String" isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")
Output:-
URL is Invalid
Test with Example_2:
Check if the string “https://www.managementbliss.com” is a valid URL.
let _string1 = "https://www.managementbliss.com" isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")
Output:-
URL is Valid
Read More:
- Javascript: Replace special characters in a string
- Javascript: Replace all occurrences of string (4 ways)
- Javascript: String replace all spaces with underscores (4 ways)
- Javascript check if string contains substring
- Javascript: Check if string is empty (6 ways)
We hope this article helped you to check if the javascript string is a valid URL. Good Luck !!!