best way to split a string and get url values using javascript
I have string which is开发者_StackOverflow中文版 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.
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).
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];
}
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
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' }
精彩评论