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

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


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.


Okay so to make a pipe you would make a pipe component consisting of

  import { Pipe, PipeTransform } from '@angular/core';    @Pipe({name: 'linkify'})    export class LinkifyPipe implements PipeTransform {      transform(link: string): string {        return this.linkify(link);      }      private linkify(plainText): string{        let replacedText;        let replacePattern1;        let replacePattern2;        let replacePattern3;        //URLs starting with http://, https://, or ftp://        replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;        replacedText = plainText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');        //URLs starting with "www." (without // before it, or it'd re-link the ones done above).        replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;        replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');        //Change email addresses to mailto:: links.        replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;        replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');        return replacedText;       }    }

then import this like u would a directive, pass it to the

pipes: [LinkifyPipe]

and interpolate like this

{{url | linkify}}


you should use this pipe in this way:

<div [innerHtml]="note.title | linkify"></div>