简体   繁体   中英

How can I get URI parameters - query string with JavaScript?

I am new at using javascript. For example, I have following url: index.jsp?page=home&lang=eng how can I extract parameters home and eng from the above url?

Question also answered: How can I get query string values in JavaScript?

To parse an url's parameters:

var url = 'index.jsp?page=home&lang=eng';

var parse = function (url) {
    var getQuery = url.substring(url.indexOf('?') + 1);
    var parts = getQuery.split('&');
    var key = null;
    var value = null;
    var result = {};
    for (var i = 0; i < parts.length; i++) {
        var keyValue = parts[i].split('=');
        key = keyValue[0];
        value = keyValue[1];
        result[key] = value;
    }
    return result;
};

The output of parse(url) would be an object that has the following structure:

{
    page: "home",
    lang: "eng"
}

Easy way to extract the exact URL param you want and will return "" empty string when can't find the paramter you search for:

function getUrlParam(param){
 var value = decodeURIComponent(
  (RegExp(param + '=' + '(.+?)(&|$)').exec(location.search)||["",""])[1]);
 return value;
} 

page_value = getUrlParam("page");    // home
lang_value = getUrlParam("lang");    // eng

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM