How to check if url scheme is present in a url string javascript

javascript, regex

Solution

You can do it quite easily with a little bit of regex. The pattern `/^[a-z0-9]+:\/\//` will be able to extract it.

If you just want to test if it has it, use `pattern.test()` to get a boolean:

/^[a-z0-9]+:\/\//.test(url); // true

If you want what it is, use `url.match()` and wrap the protocol portion in parentheses:

url.match(/^([a-z0-9]+):\/\//)[1] // https

Here is a runnable example with a few example URLs.

const urls = ['file://test.com', 'http://test.com', 'https://test.com', 'example.com?http'];

console.log(
  urls.map(url => (url.match(/^([a-z0-9]+):\/\//) || [])[1])
);

Problem

I am trying to solve an issue where I need to know if there is a URL scheme (not limited to http, https) prepended to my url string. I could do `link.indexOf(://)`; and then take the substring of anything before the "://", but if I have a case for eg: ``` example.com?url=http://www.eg.com ``` in this case, the substring will return me the whole string i.e. `example.com?url=http` which is incorrect. It should return me "", since my url does not have a protocol prepended. I need to find out whether the url is prepended with a protocol or not.

Original source