Extract the parameters from the URL and convert the object to the URL query parameter implementation code _JAVASCRIPT tips

Source: Internet
Author: User
First, extract the parameters from the URL

There are the following strings:

var linkurl = ' http://localhost:8080/String/string_6.html nickname = small Xishan son &age=24#id1 ';
For a real URL address, you can use JS to read the relevant information in location to obtain some information, listed below:
Copy Code code as follows:

Location.origin:http://localhost "Domain"
Location.pathname:/project_js/javascript/js_basic/demo/string/string_6.html "url path"
Location.host:localhost "host + port"
Location.hostname:localhost "host name"
Location.port: "Port"
Location.search:? name=xesam "Query string"
Location.hash: #age "anchor points"
Location.href:http://localhost/project_js/javascript/js_basic/demo/string/string_6.html?name=xesam#age "Full Form"
Location.protocol:http "Agreement"

In which, the extraction of parameters from the URL is mainly used to location.search. For general purposes, however, we do not read Location.search and handle strings directly.

After the string query string is extracted, it is converted to the form of an object.

Let's discuss several query string scenarios:

(1) Nickname = Small Xishan son &age=24#id1-->{nickname: ' Xiao Xi Shan zi ', Age: ' 24 '}

(2)? nickname &age=24#id1 '; -->{Nickname: undefined,age: ' 24 '}

(3)? = Xiao Xi Shan zi &age=24#id1-->{age: ' 24 '}

(4)? nickname = Small Xishan Zi = another &age=24&age=24#id1-->{nickname: ' small Xishan son = Another ', age:[' 24 ', ' 24 ']}
Copy Code code as follows:

function Toqueryparams () {
var search = This.replace (/^\s+/, '). Replace (/\s+$/, '). Match (/([^?#]*) (#.*) $/);//extract location.search '? ' The back part
if (!search) {
return {};
}
var searchstr = search[1];
var searchhash = searchstr.split (' & ');

var ret = {};
for (var i = 0, len = searchhash.length i < len; i++) {//This can call each method
var pair = Searchhash[i];
if ((pair = pair.split (' = ')) [0]) {
var key = decodeURIComponent (Pair.shift ());
var value = pair.length > 1? Pair.join (' = '): pair[0];
Console.log ()
if (value!= undefined) {
Value = decodeuricomponent (value);
}
if (key in ret) {
if (ret[key].constructor!= Array) {
Ret[key] = [Ret[key]];
}
Ret[key].push (value);
}else{
Ret[key] = value;
}
}
}
return ret;
}
Console.dir (Toqueryparams.call (Linkurl));

The above is basically the implementation of the Toqueryparams in prototype, the above another step is to use ' = ' to split the parameters, and then splicing in value. You can also use substring to achieve:
Copy Code code as follows:

function Toqueryparams () {
var search = This.replace (/^\s+/, '). Replace (/\s+$/, '). Match (/([^?#]*) (#.*) $/);
if (!search) {
return {};
}
var searchstr = search[1];
var searchhash = searchstr.split (' & ');

var ret = {};
Searchhash.foreach (function (pair) {
var temp = ';
if (temp = (pair.split (' = ', 1)) [0]) {
var key = decodeURIComponent (temp);
var value = pair.substring (key.length + 1);
if (value!= undefined) {
Value = decodeuricomponent (value);
}
if (key in ret) {
if (ret[key].constructor!= Array) {
Ret[key] = [Ret[key]];
}
Ret[key].push (value);
}else{
Ret[key] = value;
}
}
});
return ret;
}
Console.dir (Toqueryparams.call (Linkurl));


One, object conversion to URL query parameters

object to the URL query parameter is a bit cumbersome. However, because it is converted to a query parameter form, only nested objects can be processed, and child objects cannot be processed. The principle is toqueryparams reverse operation.
Copy Code code as follows:

function Toquerypair (key, value) {
if (typeof value = = ' undefined ') {
Return key;
}
Return key + ' = ' + encodeuricomponent (value = = null? ": String (value));
}
function toquerystring (obj) {
var ret = [];
for (var key in obj) {
Key = encodeURIComponent (key);
var values = Obj[key];
if (values && values.constructor = = array) {//arrays
var queryvalues = [];
for (var i = 0, Len = values.length, value i < Len; i++) {
Value = Values[i];
Queryvalues.push (Toquerypair (key, value));
}
ret = Ret.concat (queryvalues);
}else{//String
Ret.push (Toquerypair (key, values));
}
}
Return Ret.join (' & ');
}
Console.log (toquerystring ({
Name: ' Xesam ',
Age:24
})); Name=xesam&age=24
Console.log (toquerystring ({
Name: ' Xesam ',
Age: [24,25,26]
})); Name=xesam&age=24&age=25&age=26

The real source code uses the inject method, but in the enumerable section, the above is replaced.

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.