How to get URL parameters using JavaScript

This post shows you how to get parameter value from the current URL using JavaScript.

url-helper.js
function getUrlParameter(strParam) {
    // the current url
    var url = window.location.href;
    
    // remove anchor link if it exists
    url = url.replace(/#[\w-]+/i, ''); 
    
    // return an empty string if the url has no any parameters
    var paramsPattern = new RegExp(/\?+/g);
    if (!paramsPattern.test(url)) {
      return '';
    }
    
    // parameter value
    var paramValue = '';
    
    // extract parameter value from the url
    var queryString = url.split('?');
    var params = queryString[1].split('&');
    for (var i = 0; i < params.length; i++) {
        var pattern = '^('+strParam+')=(.+)';
        var regExp = new RegExp(pattern, 'i');
        var res = params[i].match(regExp);
        if (null !== res) {
            paramValue = res[2];
            break;
        }
    }

    return paramValue;
}

Use the function:

// url: https://example.com/post?id=223&name=bar
console.log(getUrlParameter('id')); // 223

// url: https://example.com/post?id=223&name=bar#top
console.log(getUrlParameter('name')); // bar

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x