JS converts URL parameters to JSON format example

Source: Internet
Author: User
Tags json

I remember using JS to convert the URL parameter to an array method I've written before, results yesterday to interview, there is also the interview topic, and then do not know the head suddenly bad, then unexpectedly did not have minutes to write out, feeling has no face to the folks, now rewrite again, then notes,

The code is as follows:

Www.111cn.net
function GetParam (url= ')
{
if (url= ')
{
var url = window.location.href;
}
var index = Url.indexof ('? ')//Get? Character position
url = url.substr (index+1); Intercept the URL parameter section
var arr = new Array ();
arr = Url.split (' & '); Separating the parameters

var str = ' [{';
Converts a parameter array part to JSON data
for (Var i=0;i<arr.length;i++)
{
var index1 = arr[i].indexof (' = ');
Determine if the last argument has a value
if (index1 = = 1)
{
str+= ', "' +arr[i]+ '": "';
Continue
}
var key = Arr[i].substr (0,INDEX1);
var val = arr[i].substr (index1+1);
var str1= ', ';
if (i==0)
{
str1 = ';
}
str+=str1+ ' "' +key+ '": ' + ' "' +val+ '";
}

Return str+ '}] ';
}

Very simple code, a look at it, if you do not pass in the parameter, then the default get the current page URL parameter to JSON data, if the URL, the incoming URL of the parameter part to JSOM data.

This code to read, not to mention what advanced knowledge, purely just JS arrays, strings, JSON conversion, processing some of the most basic functions; Other interviewers are also looking at basic skills

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.