Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a JavaScript string is a URL

Is there a way in JavaScript to check if a string is a URL?

RegExes are excluded because the URL is most likely written like stackoverflow; that is to say that it might not have a .com, www or http.

like image 941
Bruno Avatar asked Apr 19 '11 13:04

Bruno


People also ask

How do you check if a string is a URL JavaScript?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

How do you check if a URL has a string?

Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() . Therefore, the argument of indexOf should be your search string.

Is string a URL?

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.

Is a valid URL?

A URL is a valid URL if at least one of the following conditions holds: The URL is a valid URI reference [RFC3986]. The URL is a valid IRI reference and it has no query component. [RFC3987]


2 Answers

If you want to check whether a string is valid HTTP URL, you can use URL constructor (it will throw on malformed string):

function isValidHttpUrl(string) {   let url;      try {     url = new URL(string);   } catch (_) {     return false;     }    return url.protocol === "http:" || url.protocol === "https:"; } 

Note: Per RFC 3886, URL must begin with a scheme (not limited to http/https), e. g.:

  • www.example.com is not valid URL (missing scheme)
  • javascript:void(0) is valid URL, although not an HTTP one
  • http://.. is valid URL with the host being .. (whether it resolves depends on your DNS)
  • https://example..com is valid URL, same as above
like image 112
Pavlo Avatar answered Oct 04 '22 08:10

Pavlo


A related question with an answer

Or this Regexp from Devshed:

function validURL(str) {   var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol     '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name     '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address     '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path     '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string     '(\\#[-a-z\\d_]*)?$','i'); // fragment locator   return !!pattern.test(str); } 
like image 37
Tom Gullen Avatar answered Oct 04 '22 09:10

Tom Gullen