0

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?

5
  • why would you need ajax for that..? Or did i get you wrong..! Commented Mar 8, 2013 at 9:06
  • 1
    I think he means JavaScript. Some people use that term interchangeably..... Commented Mar 8, 2013 at 9:11
  • I can get parameters by using request.getParameter() with java but I want to do that with jquery Commented Mar 8, 2013 at 9:11
  • 1
    possible duplicate of How can I get query string values? Commented Mar 8, 2013 at 9:12
  • You mean use ajax to get string values? not js? Commented Mar 8, 2013 at 9:24

2 Answers 2

3

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"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.