// Prepends "http://" to a URL that doesn't already contain "http://"
const prependUrlScheme = url => {
// https://stackoverflow.com/a/3543261/3837223
if (!/^https?:\/\//i.test(url)) {
return 'http://' + url;
}
return url;
};
const hasTopLevelDomain = url => {
// https://stackoverflow.com/a/34695026/3837223
const parser = document.createElement('a');
parser.href = url;
return /^.*\..*$/.test(parser.hostname);
};
// Return a minimally valid web url based on input string. Or null if input is invalid.
const ensureValidUrl = originalUrl => {
const url = prependUrlScheme(originalUrl);
return hasTopLevelDomain(url) ? url : null;
};
export default ensureValidUrl;
Last active
January 8, 2019 04:14
-
-
Save mnishiguchi/5932864127b230450e379ff6519e3681 to your computer and use it in GitHub Desktop.
JS - Ensure valid web url - Prepend url scheme if necessary
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment