0

I have string which is in url like below

?type=english&time=today

I want to get the values of type and time and curently doing like below

var str="?type=english&time=today";

var spt =str.split("&");
var typeval =spt[0].split("=")[1];
var timeval =spt[1].split("=")[1];

document.write(" type :"+typeval+" time : "+timeval);

What is the efficient way to get the values using javascript.

2
  • possible duplicate of JavaScript query string Commented Jul 11, 2011 at 19:25
  • @Daniel the question is certainly a dup, but the answers are somewhat outdated. Commented Jul 11, 2011 at 19:30

4 Answers 4

5

Use jQuery BBQ's $.deparam function.

var str='type=english&time=today',
    obj = $.deparam(str),
    typeval = obj.type, // 'english'
    timeval = obj.time; // 'today'

It works with all sorts of fancy URL-encoded data structures (see the linked examples).

Sign up to request clarification or add additional context in comments.

2 Comments

+1 For API reference, but ... icky style! Heh, I know, you'll just chide in with how I need more semicolons ;-)
@Matt thanks for jQuery reference..it's neat and less code is required.
1

You can use the gup function- get url parameters:

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];

}

Comments

0

I always use this script:

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

then

var hash = getUrlVars();
alert(hash['type']);

will give 'english'

it's easily adaptable to what you want

Comments

0
var obj = {},
    str = "?type=english&time=today";

$.each(str.split(/&|\?/), function(){
    var tmp = this.split('=');
    ( tmp.length>1 ) && ( obj[ tmp[0] ] = tmp[1] );
})

// obj = { type : 'english', time : 'today' }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.