我一直在尝试找出一种解决方案,将链接前没有http://或https:// 的所有 href 替换为带有http://的附加链接版本。
目前我有这样的事情:
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;
}
任何帮助将不胜感激。请解释您的答案的正则表达式如何工作。我发现了很多与此类似的问题,但是对于我找到的所有解决方案,当我尝试这样做时,input.match它会返回匹配的href两次(如果有),但如果有两个hrefs,则它会返回垃圾。
这是输入:
<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>
和预期的输出:
<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>
长风秋雁
慕尼黑的夜晚无繁华
相关分类