Extracting params from urls

javascript_logo.pngImagine you have a script tag and that script tag is passed a value, the script that was run needs to get the parameter accountName:

 

 

 

 

<script src="/myClass/Controller.js?accountName=Joe&id=5"></script>

You can access accountName=Joe inside the Controller.js javascript.

function getAccountName() {
   //NOTE Since older browsers and IE doesn't support document.currentScript.getAttribute('src')
   //you can't use that

    let value = "";
    //IE and EDGE can't use the case-insensitive 'i' in this selector
    const path = $('script[src*="accountName="]').attr("src"); //Look for the script tag of this script and get the URL

     const regex = /(?<name>accountName=)(?<value>.+)&/gm;
    var m = regex.exec(path);
    if (m && m.length) {
        value = m[2];
    }
 
    return value;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s