How to display matching text in bold in Salesforce using Lightning Web Component(LWC)?

How to display matching text in bold in Salesforce using Lightning Web Component(LWC)?

Sample Code:

HTML:

<template>
    <lightning-card title="Bold Matching Text">
        <div onkeyup={handleKeyUp} class="slds-m-around_medium">
            <lightning-input
                label="Search"
                type="search"
                onchange={handleChange}
                value={searchKey}
            ></lightning-input>
        </div>
        <div class="slds-box">
            <div class="slds-m-around_medium">                              
                <lightning-formatted-rich-text value={formattedText}>
                </lightning-formatted-rich-text>  
            </div>
        </div>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';

export default class SampleLWC extends LightningElement {
        
    tempformattedTex = 'Testing Sample Example';
    formattedText = 'Testing Sample Example';  
    searchKey;

    handleChange( event ) {

        this.searchKey = event.detail.value;
        console.log( 'searchKey is', this.searchKey );
        this.formattedText = this.tempformattedTex.replace( new RegExp( this.searchKey, 'ig' ),( value ) => `<b>${value}</b>` );   

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply