This post explains how to use regex in LWC. Below is demo of output :
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 { LightningElement, track } 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 :
- 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.
- MyText : In this variable you have to pass the string in which you want to apply the pattern.
- Result : This variable is used to store results. MyText.match(myReg); is used to find pattern from string.
Output :
Thanks,
Lovesalesforceyes
Lovesalesforceyes
No comments:
Post a Comment