github.com/MontFerret/ferret@v0.18.0/e2e/pages/dynamic/utils/qs.js (about) 1 'use strict'; 2 3 var has = Object.prototype.hasOwnProperty 4 , undef; 5 6 /** 7 * Decode a URI encoded string. 8 * 9 * @param {String} input The URI encoded string. 10 * @returns {String} The decoded string. 11 * @api private 12 */ 13 function decode(input) { 14 return decodeURIComponent(input.replace(/\+/g, ' ')); 15 } 16 17 /** 18 * Simple query string parser. 19 * 20 * @param {String} query The query string that needs to be parsed. 21 * @returns {Object} 22 * @api public 23 */ 24 export function parse(query) { 25 var parser = /([^=?&]+)=?([^&]*)/g 26 , result = {} 27 , part; 28 29 while (part = parser.exec(query)) { 30 var key = decode(part[1]) 31 , value = decode(part[2]); 32 33 // 34 // Prevent overriding of existing properties. This ensures that build-in 35 // methods like `toString` or __proto__ are not overriden by malicious 36 // querystrings. 37 // 38 if (key in result) continue; 39 result[key] = value; 40 } 41 42 return result; 43 } 44 45 /** 46 * Transform a query string to an object. 47 * 48 * @param {Object} obj Object that should be transformed. 49 * @param {String} prefix Optional prefix. 50 * @returns {String} 51 * @api public 52 */ 53 export function stringify(obj, prefix) { 54 prefix = prefix || ''; 55 56 var pairs = [] 57 , value 58 , key; 59 60 // 61 // Optionally prefix with a '?' if needed 62 // 63 if ('string' !== typeof prefix) prefix = '?'; 64 65 for (key in obj) { 66 if (has.call(obj, key)) { 67 value = obj[key]; 68 69 // 70 // Edge cases where we actually want to encode the value to an empty 71 // string instead of the stringified value. 72 // 73 if (!value && (value === null || value === undef || isNaN(value))) { 74 value = ''; 75 } 76 77 pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(value)); 78 } 79 } 80 81 return pairs.length ? prefix + pairs.join('&') : ''; 82 }