angulartypescriptangular-materialtypescript2.0

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


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:test@test.com">test@test.com</a>  info </p>";

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

<a aria-label="test@test.com" href="mailto:test@test.com">test@test.com</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?


Solution

  • 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:test@test.com">test@test.com</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:test@test.com'>test@test.com</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/