data.testString contains data like below, data.test" /> data.testString contains data like below, data.test" /> data.testString contains data like below, data.test"/>

Extract href from string and again bind the updated data to the element in Angular

79 Views Asked by At

I am getting one string like this in innerHtml

<div class="wrapper" [innerHTML]="data.testString">

data.testString contains data like below,

data.testString="<p>some info, email <a href="mailto:[email protected]">[email protected]</a>  info </p>";

I want to add aria-label for the anchor tag.

<a aria-label="[email protected]" href="mailto:[email protected]">[email protected]</a>

so I have added below code in .ts file

ngAfterViewInit(): void {

    var myData = this.data.testString;
    var element = myData!.match!(/href="([^"]*)/)![1];
    
   
    var ariaLabel = "EmailId " + element;
    
    this.data.testString=
    this.data.testString!.replace('<a', '<a aria-label = "' + ariaLabel + '" ');
      
  }
}

But I am getting below error

global-error-handler.ts:26 TypeError: Cannot assign to read only property 'testString' of object '[object Object]'

How to resolve this?

1

There are 1 best solutions below

0
Mushu8 On BEST ANSWER

I'm not sure to understand all but below might help you :

  1. String character escaping

var testString="<p>some info, email <a href="mailto:[email protected]">[email protected]</a> info </p>";

There is a quote issue : a double-quoted string cannot contain double-quotes unless escaped by the \ character (cf. https://www.w3schools.com/js/js_strings.asp -> Escape Character section)

You may fix this issue by replacing some double quotes by simple quotes :

"<p>some info, email <a href='mailto:[email protected]'>[email protected]</a> info </p>"

  1. Regular expression

var href = datar!.match!(/href="([^"]*)/)![1];

Not sure this is the pattern you need. Try instead :

var href = datar!.match!(/href=\'mailto:([a-z@.]+)'/)![1];

  1. DOM element manipulation

About adding the aria-label attribute to the , you would better go with Angular nativeElement.setAttribute(key, value) native javascript querySelector (cf. https://indepth.dev/posts/1336/how-to-do-dom-manipulation-properly-in-angular and https://angular.io/guide/property-binding)

Finally I would highly recommend the use of RegExr to test your regular expressions https://regexr.com/7ep0u as well as jsfiddle.net to test your javascript in a safe environment : https://jsfiddle.net/nkarfgx3/