Saturday, July 18, 2020

Get URL Parameters in Lightning Web Component

Hello All,

Today we will disscuss ,how to get parameter from query string in lwc, below we have two method for that any one we can use as.

Sample code for componet js:-

import { LightningElement , track } from 'lwc';

export default class UrlParamInLWC extends LightningElement {
 

    connectedCallback() { 
      const param = 'test';
      const paramValue = this.getUrlParamValue(window.location.href, param);
      let param1 = this.getUrlParameter('param1');
      console.log('Found Parameter value for param1'+param1);
    }
/* first way*/
     getUrlParameter(name)
{
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
       var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
       var results = regex.exec(location.search);
       return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
   }
/* Second way */
   getUrlParamValue(url, key) {
    return new URL(url).searchParams.get(key);
   }
}

No comments: