Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 717
CommonSenseCode Avatar asked Sep 01 '16 16:09

CommonSenseCode


2 Answers

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.

like image 164
tuomassalo Avatar answered Oct 10 '22 03:10

tuomassalo


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}} 
like image 36
Mark Acosta Avatar answered Oct 10 '22 01:10

Mark Acosta