mathematics-and-caffeine
mathematics-and-caffeine

Reputation: 2188

HTML: How to make URLs inside of text clickable?

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?

Upvotes: 2

Views: 508

Answers (2)

mancini0
mancini0

Reputation: 4703

Try setting the innerHtml of the relevant element:

document.getElementById("myDiv").innerHTML=makeLinksClickable(myUrl);

Upvotes: 0

Anton Marinenko
Anton Marinenko

Reputation: 2982

Keep it simple?

<div [innerHTML]="myObject ? this.myService.makeLinksClickable(myObject.text) : ''">
</div>

Upvotes: 3

Related Questions