Angular2 way of converting plain text to url (anchor links)

CommonSenseCode picture CommonSenseCode · Sep 1, 2016 · Viewed 21.4k times · Source

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?

Answer

tuomassalo picture tuomassalo · Feb 28, 2017

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.