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"



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



import { LightningElement } from "lwc";

export default class App extends LightningElement {
  recs = []

    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 => {
                element.Title.replace(new RegExp('Check', 'ig'),(value)=>`<mark>${value}</mark>`);

2 Answers 2


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>

You can also use a quick algorithm to break the parts up:

element.highlights = element.Title.replaceAll(RegExp(`(${searchTerm})`, "ig"), "\0$1\0")
    (p, v) => {
      if (p.normal == undefined) {
        p.normal = v;
      } else {
        p.values.push({ key: p.values.length, normal: p.normal, mark: v });
        p.normal = undefined;
      return p;
    { values: [] }

Which you can then display in your template:

<template for:each={recs} for:item="rec">
  <div key={rec.Title} class="slds-card">
    <template for:each={rec.highlights} for:each="highlight" >
      <span key={highlight.index} class="normal">{highlight.normal}</span>
      <mark key={highlight.index} class="bold">{highlight.mark}</mark>

This has the advantage of not dealing with HTML directly in your JavaScript, at the cost of more markup.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .