I have been trying to figure out a solution to replace all hrefs that do not have http:// or https:// in front of a link with an appended version of the link with http:// on it.
Currently I have something like this:
static correctUrls(input: string): string {
// get all hrefs from the input
let urls = input.match('<a[^>]* href="([^"]*)"/g');
// if no urls return original input
if (!urls) {
return input;
}
// remove duplicate urls
urls = urls.filter((item, pos) => {
return urls.indexOf(item) === pos;
});
// if no urls in input
if (!urls) {
return input;
}
for (const url of urls) {
// if url does not have https
// tslint:disable-next-line: max-line-length
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 help would be greatly appreciated. Please include an explanation of how your answer's regex works. I have found lots of similar questions to this one, but with all of the solutions I have found, when I try to do input.match
it returns the matched href
twice (if there is one), but if there are two href
s then it returns rubbish.
Here is the input:
<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>
And the 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>