I sometimes have a component that can receive text like this:
text www.website.com
But I would like to convert it to a url if it is a link. Like this.
text www.website.com
I read this SO answer that suggests using 3rd party libs such as anchorme. Is there anywway to do it the angular2 way?
There are numerous problems with using simple regexes to modify HTML content.
Here's an approach that uses the linkifyjs module, which you need to npm install
. Do notice that the input is considered plain text, while output is HTML text.
import { Pipe, PipeTransform } from '@angular/core';
import linkifyStr from 'linkifyjs/string';
@Pipe({name: 'linkify'})
export class LinkifyPipe implements PipeTransform {
transform(str: string): string {
return str ? linkifyStr(str, {target: '_system'}) : str;
}
}
NB: If you need to specify the target
attributes, add eg. {target: '_system'}
as a second parameter to linkifyStr
.