I've been trying to come up with a solution to automatically add "http://" to any href links that don't already have it before the link. Here is what I currently have:
static correctUrls(input: string): string {
// extract all hrefs from the input
let urls = input.match('<a[^>]* href="([^"]*)"/g');
// if no urls found, return original input
if (!urls) {
return input;
}
// remove duplicate urls
urls = urls.filter((item, pos) => {
return urls.indexOf(item) === pos;
});
// if no urls in the input, return original input
if (!urls) {
return input;
}
for (const url of urls) {
// check if url does not start with https://
if (!url.match('^ (http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$')) {
input = input.replace(url, 'https://' + url);
}
}
return input;
}
Any assistance would be greatly appreciated. Please explain how your regex solution works. Most solutions I've come across so far return duplicate matches or behave strangely when used with input.match.
Input example:
<p> We love
<a href="https://google.com"
rel="noopener noreferrer"
target="_blank">Google</a>
and
<a href="Facebook.com"
rel="noopener noreferrer"
target="_blank">Facebook</a>.
</p>
Expected output:
<p> We love
<a href="https://google.com"
rel="noopener noreferrer"
target="_blank">Google</a>
and
<a href="https://Facebook.com"
rel="noopener noreferrer"
target="_blank">Facebook</a>.
</p>