0

I would like to have a pipe which is detecting any url in a string and creating a link with it. At the moment I created this, which seems not working:

@Pipe({name:'matchUrl'})
export class MatchUrlPipe implements PipeTransform {
    transform(value: string, arg?: any): any {
      var exp = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
      return value.replace(exp, "<a href='$1'>$1</a>");
    }
}

How can I fix it?

Ugo
  • 39
  • 1
  • 7

1 Answers1

1

Seems like there are two problems with your implementation:

  1. Your regex has the first capturing group ( $1 ) matching the 'www' part of the url. You want to change the regex like this for it to work (note the extra pair of parethesis at the start and end of the regex):

var exp = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))/g;

  1. Pipes can't render html normally. You need a trick to do that as mentioned in other questione like this. You need to assign your 'piped value' to the attribute outerHTML of a span for example (the span will not be rendered).

Plunker example

Community
  • 1
  • 1
Luca Regazzi
  • 1,345
  • 1
  • 11
  • 23
  • This regular expression will not catch new TLD (for example: https://page.online) due to the restriction to 4 characters. – andreas Mar 21 '21 at 00:43