admin管理员组

文章数量:1332865

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?url=

in this case, the substring will return me the whole string i.e. example?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.

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.?url=http://www.eg.

in this case, the substring will return me the whole string i.e. example.?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.

Share edited May 2, 2017 at 16:17 styfle 24.7k30 gold badges92 silver badges139 bronze badges asked May 2, 2017 at 15:55 user564927user564927 3051 gold badge5 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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.', 'http://test.', 'https://test.', 'example.?http'];

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

You could use the URL API which is supported in most browsers.

function getProtocol(str) {
    try {
        var u = new URL(str);
        return u.protocol.slice(0, -1);
    } catch (e) {
        return '';
    }
}

Usage

getProtocol('example.?url=http://www.eg.'); // returns ""
getProtocol('https://example.?url=http://www.eg.'); // returns "https"

You can first use validator.js to check whether the string is a valid url with a protocol. Then use JavaScript's built-in URL api to get the protocol from the url.

Let's say that the string you need to check is in the str variable.

import validator from "validator"

// Use validator.js to check if the string is a url with a protocol
const isValidUrlWithProtocol = validator.isURL(str, { require_protocol: true })
// isValidUrlWithProtocol will be true for http://example. (or https), not example.

const protocol = isValidUrlWithProtocol ? new URL(str).protocol : ""
// If isValidUrlWithProtocol is true, protocol will be "http:" (or "https:")

本文标签: regexHow to check if url scheme is present in a url string javascriptStack Overflow