Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Created November 26, 2021 00:50
Show Gist options
  • Save luan0ap/e291ae35e412cb7a0b15523eecf4ea1f to your computer and use it in GitHub Desktop.
Save luan0ap/e291ae35e412cb7a0b15523eecf4ea1f to your computer and use it in GitHub Desktop.
Prepende http/https to an URL
// https://github.com/sindresorhus/prepend-http/blob/main/index.js
function prependHttp(url, {https = true} = {}) {
if (typeof url !== 'string') {
throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof url}\``);
}
url = url.trim();
if (/^\.*\/|^(?!localhost)\w+?:/.test(url)) {
return url;
}
return url.replace(/^(?!(?:\w+?:)?\/\/)/, https ? 'https://' : 'http://');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment