🔒 Linkify refacto

This commit is contained in:
itskovacs 2025-08-06 20:00:49 +02:00
parent 04e7e3720a
commit 13284f989d

View File

@ -5,13 +5,31 @@ import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
export class LinkifyPipe implements PipeTransform { export class LinkifyPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {} constructor(private sanitizer: DomSanitizer) {}
private basicEscape(text: string): string {
return text.replace(
/[&<>"']/g,
(char) =>
({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[char]!,
);
}
transform(text: string): SafeHtml { transform(text: string): SafeHtml {
if (!text) return text; if (!text) return text;
const urlRegex = /((https?:\/\/|www\.)[^\s]+)/g; const urlRegex = /((https?:\/\/|www\.)[^\s]+)/g;
const html = text.replace(urlRegex, (url) => { const safeText = this.basicEscape(text);
return `<a href="${url}" target="_blank">${url}</a>`;
const html = safeText.replace(urlRegex, (url) => {
const href = url.startsWith("http") ? url : `https://${url}`;
return `<a href="${href}" target="_blank">${url}</a>`;
}); });
return this.sanitizer.bypassSecurityTrustHtml(html); return this.sanitizer.bypassSecurityTrustHtml(html);
} }
} }