javascript
Validate a url using regex in Javascript
If you want to check if a URL string is valid or not, you can use regular expressions in Javascript. You can test any string against that regex and it will return true if the URL is valid.
function validate_url(url) {
const url_regex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?: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*)?$/i;
return url_regex.test(url);
}
console.log( validate_url("invalidurl.com") );
// -> false
console.log( validate_url("http://validurl.com") );
// -> true
Output
false
true
function validate_url(url_str) {
var regex = /^((https?):\/\/)?([w|W]{3}\.)+[a-zA-Z0-9\-\.]{3,}\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/;
return regex.test(url_str)
}
console.log( validate_url("domain.com") );
console.log(validate_url("http://www.domain.com"));
You will also have to use "www" in your URL string to validate it otherwise it will not be valid.
Was this helpful?
Similar Posts
- Using regex to validate a phone number in Javascript
- Javascript examples to remove url from a string
- Regex for email validation in Javascript
- allows keeping the URL while rendering a different page
- Convert all characters to lowercase using toLowerCase() method in javascript
- Sort array using Array.sort() in javascript
- Get Pseudo elements using Javascript