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.

JavaGeek
  • 1,535
  • 9
  • 39
  • 63

4 Answers4

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).

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • +1 For API reference, but ... icky style! Heh, I know, you'll just chide in with how I need more semicolons ;-) –  Jul 11 '11 at 19:31
  • 1
    @Matt thanks for jQuery reference..it's neat and less code is required. – JavaGeek Jul 11 '11 at 19:36
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];

}

aviv
  • 2,719
  • 7
  • 35
  • 48
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

beardhatcode
  • 4,533
  • 1
  • 16
  • 29
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' }