sunny kushwaha
sunny kushwaha

Reputation: 51

How do i display a single word as a hyper link from complete message in angular

I am displaying a message on my angular app using interpolation. The message include name of a person too. I am using @ to specify the person name. what i want is where ever any persons name come in message which i am displaying it should be a hyper link. when click to the link person gets redirected to the person profile.

Upvotes: 3

Views: 352

Answers (1)

Ben Racicot
Ben Racicot

Reputation: 5935

You want to build a pipe directive It turns out that manipulating DOM elements is much better suited for directives and components.

Here is my working StackBlitz directive.

Regular Expression Method

I got help to find the regex /@[0-9a-zA-Z]{5,20}(?=\\s|$)/ that works:

// REGEX-MATCH AND REPLACE THE USERNAME SUBSTRING(S)
ngAfterViewInit(){
    this.initialText = this.el.nativeElement.innerText;

    this.finalText = this.initialText.replace(/@[0-9a-zA-Z]{5,20}(?=\\s|$)/, function(username) {
        return `<a href="#${username.substring(1)}">${username}</a>`;
    });

Looping Method

When looping you must test every word to check for multiple occurrences of @xxxxxxx usernames.

  • Get any group of text
  • split each word at every space
  • check each word for @xx match
  • word for @username text references
  • wrap @username instances in an tag
  • replace the element's original text with finalText
  • this does not check for special characters
  • this does not check for already wrapped @usernames

Both versions are in the StackBlitz with working innerHTML replacement.

ngAfterViewInit(){
    this.initialText = this.el.nativeElement.innerText;
    if (this.initialText && this.initialText.length > 0) {
        for (let text of this.initialText.split(" ")) {
            if (text.startsWith("@") && text.length > 1){
              this.finalText += `<a href="#${text.substring(1)}">${text}</a> `;
            } else {
              this.finalText += text + " ";
            }
        }
    }
}

Upvotes: 2

Related Questions