I cannot hand-code the <a> ... </a>
since the input is a not known string.
I came up with this:
HTMLFormattingService:
makeLinksClickable(inp: string): string {
const regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\ \$,\w] @)?[A-Za-z0-9.-] |(?:www.|[-;:&=\ \$,\w] @)[A-Za-z0-9.-] )((?:\/[\ ~%\/.\w-_]*)?\??(?:[-\ =&;%@.\w_]*)#?(?:[\w]*))?)/ig
return inp.replace(regex, '<a href="$1" target="_blank">$1</a>');
}
HTML:
<div>
{{myObject ? this.myService.makeLinksClickable(myObject.text) : ""}}
</div>
The replacing works, but the <a> ... </a>
is NOT clickable with this method! That is because <a>
not treated as a HTML element but just as text. So the users see the <a>
and </a>
and cannot click the link.
How can I fix this?
CodePudding user response:
Keep it simple?
<div [innerHTML]="myObject ? this.myService.makeLinksClickable(myObject.text) : ''">
</div>
CodePudding user response:
Try setting the innerHtml of the relevant element:
document.getElementById("myDiv").innerHTML=makeLinksClickable(myUrl);