Sunday, March 14, 2021

How to use regex in LWC

 This post explains how to use regex in LWC. Below is demo of output :

use regex in lwc

regex_In_LWC.html :



    <template>
        <lightning-input type="text" onchange ={handleValue} 
label="Enter Text">
        </lightning-input>
        <lightning-button type="submit"
            name="Apply Regex"
            label="Apply_Regex"
            onclick={handleclick}>
        </lightning-button>
    </template>


regex_In_LWC.js



    import { LightningElementtrack } from 'lwc';

    export default class Regex_In_LWC extends LightningElement {
        @track Text

        handleValue(event){
            this.Text = event.target.value;
        }
        handleclick(event){
            var myReg = /love(.*?)yes/;
            var MyText = this.Text;
            var Result = MyText.match(myReg);
            alert('after apply regex '+this.Text+' => '+Result[1]);
        }
    }


regex_In_LWC.Meta



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


 In the js file there is three variable :

  1.  myReg : In this variable you have to pass the pattern which you want to apply on string. I am giving the pattern to fetch string between love and yes.
  2. MyText : In this variable you have to pass the string in which you want to apply the pattern.
  3. Result : This variable is used to store results. MyText.match(myReg); is used to find pattern from string.
You can make your own pattern and apply it to the string.


Output :


how to use regex in lwc



Thanks, 
Lovesalesforceyes

No comments:

Post a Comment

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...