Get the current page record Id in LWC Salesforce

Sometimes we have to get the current URL or current recordId from URL. In this article, we are going to learn how we can get the current recordId from URL .

There is two ways to achieve the requirement:-

  1. Using the standard method
  2. Using Regex

Using the standard method :-


        <lightning-button variant="brand" label="Get Id" 
            title="Primary action" onclick={handleClick}
            Record Id = {recId}


import { LightningElement, track,  api } from 'lwc';

export default class getRecId extends LightningElement {
    @api recordId;
    @track recId; 

    handleClick() {
        this.recId = this.recordId;

Using Regex

Just change the getRecId.js file with the below code.

import { LightningElement, track } from 'lwc';
export default class getRecId extends LightningElement { 
    @track recId;
    //Getting the current url
    testURL = window.location.href;
    //Filtering the URL to get the Id
    newURL = this.testURL.match(/[a-z0-9]\w{4}0\w{12}|[a-z0- 
    handleClick() {
        this.recId = this.newURL;
        window.console.log('-->RecordId-->' + this.recId);


I hope the above code work for you. We will add more articles soon. So, don’t forget to subscribe our website. You can add in our WhatsApp group.

Please provide us your valuable feedback. We will appreciate your efforts.