Highlight a search word in LWC for each loop

cssjavascriptlightning-web-components

I have the below code where i want to highlight a given word .But the word is not getting highlighted. Tried using tag Below is the code. FOr this below given code, i am trying to highlight word "Check"

HTML

<template>

    <template for:each={recs} for:item="rec">
        <div key={rec.Title} class="slds-card"> {rec.Title}</div>
    </template>

</template>

JS

import { LightningElement } from "lwc";

export default class App extends LightningElement {
  recs = []
  

  connectedCallback(){
    this.recs = [{"CreatedByName":"David Guetta","CreatedDate":"6/10/2022","Id":"11111111111","showHideBy":"slds-hide","showHideclosureReason":"slds-show","Reason":"test","Status":"Subject Matter Expert Review","Title":"Check Highlight"},{"CreatedByName":"test","CreatedDate":"5/1/2022","Id":"222222222","showHideBy":"slds-hide","showHideclosureReason":"slds-show","Reason":"slds-hide","Status":"Subject Matter Expert Review","Title":"Check Highlight Check"}]
   this.recs.forEach(element => {
            if(element.Title){
                alert(element.Title)
                element.Title.replace(new RegExp('Check', 'ig'),(value)=>`<mark>${value}</mark>`);
            }
        });
  }
}

Best Answer

I think you need to assign the returned value from replace function, taken from mozilla documentation: The replace() method returns a new string with some or all matches of a pattern replaced by a replacement so try this:

element.Title = element.Title.replace(new RegExp('Check', 'ig'),(value)=>`<mark>${value}</mark>`);

Hope this helps!

EDIT: you might need to use this tag on your template:

<lightning-formatted-rich-text value={rec.Title}></lightning-formatted-rich-text>