Javascript Loop through Object Literal - javascript

I would like to iterate over the below and output a string that combines the different settings:
Loop through this:
config : {
settings : {
width: 880,
height: 495,
byline: false,
title: false,
portrait: false
}
}
And output:
var output = '&height=495&width=880&title=false&byline=false&portrait=false',
How would I go about this?

I don't know whether you explicitly want to loop, but you can simply use jQuery.param:
var output = "&" + $.param(obj.config.settings);
// I assumed `obj` contains `config`
The order may be different but for a query string that does not matter.

var attr, val, settings = config.settings,
output, count = 0;
if ('undefined' !== typeof settings) {
for (attr in settings) {
val = settings[attr];
if (0 === count) {
output = output + val;
} else {
output = output + '&' + val;
}
count += 1;
}
console.log(output);
}
Note, the above code adds the optimization where you don't add an & to the first var. I don't think you'd want that in a get var string. If you do, just change to output = output + val; starting from if to end of else.

How about this:
function print( obj ) {
return Object.keys( obj ).map( function ( name ) {
return '&' + name + '=' + obj[ name ];
}).join( '' );
}
Usage:
var output = print( obj.config.settings );
Live demo: http://jsfiddle.net/w3D9M/

Related

How can I convert a javascript dictionary to a list of html attributes?

I would like to take this:
var sneed = { feed: "and", seed: [ "formerly", "chucks" ] };
And produce this:
feed="and" seed="formerly,chucks"
But how?
It needs to work in older javascript versions.
My solution:
function arg( d = {} ) {
var sl = [];
for ( var key in d ) {
sl.push( key + '="' + d[key] + '"' );
}
return sl.join(" ");
}
The problem is, that this will quickly fail if any " is found within any of the strings, which leads me to ask if there is actually a simpler more straightforward way of doing this.
Thanks.
You can escape a string to put it inside an HTML attribute value safely and accurately by replacing the ampersand and quote character with their corresponding HTML entities:
function escapeDoubleQuotedAttributeValue(str) {
return str.replace(/&/g, "&")
.replace(/"/g, """);
}
Turning whatever objects you want to support into strings is a separate issue.
function valueToString(value) {
if (typeof value === 'string') {
return value;
}
if (Object.prototype.toString.call(value) === '[object Array]') {
return String(value);
}
throw new TypeError('Unsupported value');
}
function htmlAttributes(d) {
var attributes = [];
for (var key in d) {
var stringValue = valueToString(d[key]);
var escapedValue = escapeDoubleQuotedAttributeValue(stringValue);
attributes.push(key + '="' + escapedValue + '"');
}
return attributes.join(" ");
}
Check whether converting the value to a string results in a value containing quotes. If so, use the opposite type of quotes around the attribute value in the HTML string.
if it contains both, use double quotes as the delimiters, and replace any embedded double quotes with ".
function arg(d = {}) {
var sl = [];
for (var key in d) {
var value = d[key].toString();
var delim;
if (value.includes('"') && value.includes("'")) {
value = value.replace(/"/g, '"');
delim = '"';
} else if (value.includes('"')) {
delim = "'";
} else {
delim = '"';
}
sl.push(key + '=' + delim + value + delim);
}
return sl.join(" ");
}
console.log(arg({ feed: "and", seed: [ "formerly", "chucks" ] }));
console.log(arg({ feed: "and", seed: [ 'The "first"', "chucks" ] }));
console.log(arg({ feed: "and", seed: [ "formerly", "chuc'ks" ] }));
console.log(arg({ feed: "and", seed: [ 'for"erly', "chuc'ks" ] }));

JavaScript - Function for finding text within a string

I have a function that I use to pass over a table field name and its value. Depending on the name of the field, it either returns the contents as a link or it does not.
// Given a field name, check to see if its in our output. If so, return the formatted link
function createLink(field, val) {
var output = {
'ntid': 'https://web.internal/profile/' + val,
'email': 'mailTo:' + val
};
var i, key, keys = Object.keys(output);
for ( i = 0; i < keys.length; ++i ) {
key = keys[i];
if(field.toLowerCase() == key){
return ''+val+'';
}
}
return val;
}
Usage:
createLink('email', 'bob#stuff.com')
// returns bob#stuff.com
This also works for NTID. The issue I am having though is there are some field names that contain my values in the output such as Sup Email or Sup NTID and those are not transformed correctly.
Expected Result:
createLink('sup email', 'bob2#stuff2.com')
// returns bob#stuff.com
The Question:
How can I tweak my function to see if my field exists in the output array at all, even if it's not an exact match?
Change your function to
function createLink(field, val) {
var output = {
'ntid': 'https://web.internal/profile/' + val,
'email': 'mailTo:' + val
};
var i, key, keys = Object.keys(output);
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if ((field.toLowerCase()).includes(key)) {
return '' + val + '';
}
}
return val;
}
console.log(createLink('sup email', 'bob2#stuff2.com') )
Notice the code if ((field.toLowerCase()).includes(key)) {
This will check for your key substring in the string
What you're implementing is the Strategy Pattern. The Strategy Pattern relies on some form of behaviour-switching depending on the inputs to the method. In your case, that switching is based on the first argument.
What you don't want to do is what your questions asks how to do. You don't want to assume every field name in your application which contains "email" or some other string is guaranteed to be an email address, handled by the same strategy.
Create a table of field names and strategies to use for the display of each of these fields; and use an "enum-ish" object as the definition of the strategies.
function create_link(field, val) {
const strategy = create_link.Field_Strategies[field];
if (typeof strategy === 'undefined') {
console.log("Using default strategy");
return val;
}
console.log("Using " + strategy);
switch (strategy) {
case create_link.Strategies.EMAIL:
return '' + val + '';
case create_link.Strategies.NTID:
return '<a href="https://web.internal/profile/' +
val + '" target="_blank">' + val + '</a>';
case create_link.Strategies.SOME_FIELD:
return '<a href="http://example.com/some/path/' +
encodeURIComponent(val) +
'" target="_blank">' + val + '</a>';
}
}
create_link.Strategies = {
EMAIL: "email strategy",
NTID: "ntid strategy",
SOME_FIELD: "somefield strategy"
};
create_link.Field_Strategies = {
"Sup email": create_link.Strategies.EMAIL,
"E-mail": create_link.Strategies.EMAIL,
"Email": create_link.Strategies.EMAIL,
"NTID": create_link.Strategies.NTID,
"Foobar baz": create_link.Strategies.SOME_FIELD
};
console.log(create_link("foo","foofoofoo"));
console.log(create_link("Sup email","supervisor#example.com"));
console.log(create_link("E-mail","foo#example.com"));
console.log(create_link("Email","bar#example.com"));
console.log(create_link("NTID","10983409509734"));
console.log(create_link("Foobar baz","Aleph null"));
You could use String.prototype.indexOf.
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value...Returns -1 if the value is not found.
So your code would then look like:
// Given a field name, check to see if its in our output. If so, return the formatted link
function createLink(field, val) {
var output = {
'ntid': 'https://web.internal/profile/' + val,
'email': 'mailTo:' + val
};
var i, key, keys = Object.keys(output);
for ( i = 0; i < keys.length; ++i ) {
key = keys[i];
if(field.toLowerCase().indexOf(key) >= 0){ //CHANGE HERE
return ''+val+'';
}
}
return val;
}

Is there any native function to convert json to url parameters?

I need convert json object to url form like: "parameter=12&asd=1"
I done with this:
var data = {
'action':'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2' : 3
};
var string_=JSON.stringify(data);
string_=string_.replace(/{/g, "");
string_=string_.replace(/}/g, "");
string_=string_.replace(/:/g, "=")
string_=string_.replace(/,/g, "&");
string_=string_.replace(/"/g, "");
But i wonder if there any function in javascript or in JSON object to do this?
Use the URLSearchParams interface, which is built into browsers and Node.js starting with version 10, released in 2018.
const myParams = {'foo': 'hi there', 'bar': '???'};
const u = new URLSearchParams(myParams).toString();
console.log(u);
Old answer: jQuery provides param that does exactly that. If you don't use jquery, take at look at the source.
Basically, it goes like this:
url = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}).join('&')
Using ES6 syntax:
var data = {
'action':'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2' : 3
};
let urlParameters = Object.entries(data).map(e => e.join('=')).join('&');
console.log(urlParameters);
I made an implementation that support nested objects and arrays i.e.
var data = {
users: [
{
"name": "jeff",
"tasks": [
"Do one thing",
"Do second thing"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
Will be:
users[0][name]=jeff&users[0][tasks][0]=Do%20one%20thing&users[0][tasks][1]=Do%20second%20thing&users[1][name]=rick&users[1][tasks][0]=Never%20gonna%20give%20you%20up&users[1][tasks][1]=Never%20gonna%20let%20you%20down
So, here's the implementation:
var isObj = function(a) {
if ((!!a) && (a.constructor === Object)) {
return true;
}
return false;
};
var _st = function(z, g) {
return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
};
var fromObject = function(params, skipobjects, prefix) {
if (skipobjects === void 0) {
skipobjects = false;
}
if (prefix === void 0) {
prefix = "";
}
var result = "";
if (typeof(params) != "object") {
return prefix + "=" + encodeURIComponent(params) + "&";
}
for (var param in params) {
var c = "" + prefix + _st(param, prefix);
if (isObj(params[param]) && !skipobjects) {
result += fromObject(params[param], false, "" + c);
} else if (Array.isArray(params[param]) && !skipobjects) {
params[param].forEach(function(item, ind) {
result += fromObject(item, false, c + "[" + ind + "]");
});
} else {
result += c + "=" + encodeURIComponent(params[param]) + "&";
}
}
return result;
};
var data = {
users: [{
"name": "jeff",
"tasks": [
"Do one thing",
"Do second thing"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
document.write(fromObject(data));
You don't need to serialize this object literal.
Better approach is something like:
function getAsUriParameters(data) {
var url = '';
for (var prop in data) {
url += encodeURIComponent(prop) + '=' +
encodeURIComponent(data[prop]) + '&';
}
return url.substring(0, url.length - 1)
}
getAsUriParameters(data); //"action=actualiza_resultado&postID=1&gl=2&gl2=3"
Something I find nicely looking in ES6:
function urlfy(obj) {
return Object
.keys(obj)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
.join('&');
}
Later update (same thing, maybe a bit cleaner):
const urlfy = obj => Object
.keys(obj)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]))
.join('&');
Like #georg said, you can use JQuery.param for flat objects.
If you need to process complex objects, you can use JsonUri, a python package that does just that. There is JavaScript library for it as well
Disclaimer: I am the author of JSONURI
Edit: I learned much later that you can also just base64 encode your payload - most languages as support for base64 encoding/decoding
Example
x = {name: 'Petter', age: 47, places: ['Mozambique', 'Zimbabwe']}
stringRep = JSON.stringify(x)
encoded = window.btoa(stringRep)
Gives you eyJuYW1lIjoiUGV0dGVyIiwiYWdlIjo0NywicGxhY2VzIjpbIk1vemFtYmlxdWUiLCJaaW1iYWJ3ZSJdfQ==, which you can use as a uri parameter
decoded = window.atob(encoded)
originalX = JSON.parse(decoded)
Needless to say, it comes with its own caveats
But i wonder if there any function in javascript
Nothing prewritten in the core.
or json to do this?
JSON is a data format. It doesn't have functions at all.
This is a relatively trivial problem to solve though, at least for flat data structures.
Don't encode the objects as JSON, then:
function obj_to_query(obj) {
var parts = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return "?" + parts.join('&');
}
alert(obj_to_query({
'action': 'actualiza_resultado',
'postID': 1,
'gl': 2,
'gl2': 3
}));
There isn't a standard way to encode complex data structures (e.g. with nested objects or arrays). It wouldn't be difficult to extend this to emulate the PHP method (of having square brackets in field names) or similar though.
This one processes arrays with by changing the nameinto mutiple name[]
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
Best solution for Vanilla JavaScript:
var params = Object.keys(data)
.filter(function (key) {
return data[key] ? true : false
})
.map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
})
.join('&');
PS: The filter is used here to remove null or undefined parameters. It makes the url look cleaner.
The custom code above only handles flat data. And JQuery is not available in react native. So here is a js solution that does work with multi-level objects and arrays in react native.
function formurlencoded(data) {
const opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let sorted = Boolean(opts.sorted),
skipIndex = Boolean(opts.skipIndex),
ignorenull = Boolean(opts.ignorenull),
encode = function encode(value) {
return String(value).replace(/(?:[\0-\x1F"-&\+-\}\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g, encodeURIComponent).replace(/ /g, '+').replace(/[!'()~\*]/g, function (ch) {
return '%' + ch.charCodeAt().toString(16).slice(-2).toUpperCase();
});
},
keys = function keys(obj) {
const keyarr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Object.keys(obj);
return sorted ? keyarr.sort() : keyarr;
},
filterjoin = function filterjoin(arr) {
return arr.filter(function (e) {
return e;
}).join('&');
},
objnest = function objnest(name, obj) {
return filterjoin(keys(obj).map(function (key) {
return nest(name + '[' + key + ']', obj[key]);
}));
},
arrnest = function arrnest(name, arr) {
return arr.length ? filterjoin(arr.map(function (elem, index) {
return skipIndex ? nest(name + '[]', elem) : nest(name + '[' + index + ']', elem);
})) : encode(name + '[]');
},
nest = function nest(name, value) {
const type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : typeof value === 'undefined' ? 'undefined' : typeof(value);
let f = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
if (value === f) f = ignorenull ? f : encode(name) + '=' + f; else if (/string|number|boolean/.test(type)) f = encode(name) + '=' + encode(value); else if (Array.isArray(value)) f = arrnest(name, value); else if (type === 'object') f = objnest(name, value);
return f;
};
return data && filterjoin(keys(data).map(function (key) {
return nest(key, data[key]);
}));
}
The conversion from a JSON string to a URL query string can be done in a single line:
const json = '{"action":"actualiza_resultado","postID":1,"gl":2,"gl2":3}';
const queryString = new URLSearchParams(JSON.parse(json)).toString();
queryString would then be set to "action=actualiza_resultado&postID=1&gl=2&gl2=3".
Based on georg's answer, but also adding ? before the string and using ES6:
const query = !params ? '': Object.keys(params).map((k, idx) => {
let prefix = '';
if (idx === 0) {
prefix = '?';
}
return prefix + encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
}).join('&');
As most of the answers only convert flat objects to query parameters, I would like to share mine.
This function can handle flat objects, as well as nested arrays/objects while only using plain JS.
function incapsulateInBrackets(key)
{
return '[' + key + ']';
}
function encode(object, isSubEncode=false, prefix = '')
{
let parts = Object.keys(object).map( (key) => {
let encodedParts = [];
if(Array.isArray(object[key]))
{
object[key].map(function(innerKey, index){
encodedParts.push( encode(object[key][index], true, prefix + key + incapsulateInBrackets(index)));
});
}
else if(object[key] instanceof Object)
{
Object.keys(object[key]).map( (innerKey) => {
if(Array.isArray(object[key][innerKey]))
{
encodedParts.push( encode(object[key][index], true, prefix + incapsulateInBrackets(key) + incapsulateInBrackets(innerKey)) );
}
else
{
encodedParts.push( prefix + incapsulateInBrackets(key) + incapsulateInBrackets(innerKey) + '=' + object[key][innerKey] );
}
});
}
else
{
if(isSubEncode)
{
encodedParts.push( prefix + incapsulateInBrackets(key) + '=' + object[key] );
}
else
{
encodedParts.push( key + '=' + object[key] );
}
}
return encodedParts.join('&');
});
return parts.join('&');
}
Make a utility if you have nodejs
const querystring = require('querystring')
export function makeQueryString(params): string {
return querystring.stringify(params)
}
import example
import { makeQueryString } from '~/utils'
example of use
makeQueryString({
...query,
page
})
Read the latest documentation here.

Add method to string class

I'd like to be able to say something like this in javascript :
"a".distance("b")
How can I add my own distance function to the string class?
You can extend the String prototype;
String.prototype.distance = function (char) {
var index = this.indexOf(char);
if (index === -1) {
alert(char + " does not appear in " + this);
} else {
alert(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};
... and use it like this;
"Hello".distance("H");
See a JSFiddle here.
String.prototype.distance = function( arg ) {
// code
};
Minimal example:
No ones mentioned valueOf.
==================================================
String.prototype.
OPERATES_ON_COPY_OF_STRING = function (
ARGUMENT
){
//:Get primitive copy of string:
var str = this.valueOf();
//:Append Characters To End:
str = str + ARGUMENT;
//:Return modified copy:
return( str );
};
var a = "[Whatever]";
var b = a.OPERATES_ON_COPY_OF_STRING("[Hi]");
console.log( a ); //: [Whatever]
console.log( b ); //: [Whatever][Hi]
==================================================
From my research into it, there is no way to edit the string in place.
Even if you use a string object instead of a string primitive.
Below does NOT work and get's really weird results in the debugger.
==================================================
String.prototype.
EDIT_IN_PLACE_DOES_NOT_WORK = function (
ARGUMENT
){
//:Get string object:
var str = this;
//:Append Characters To End:
var LN = str.length;
for( var i = 0; i < ARGUMENT.length; i++){
str[LN+i] = ARGUMENT[ i ];
};
};
var c = new String( "[Hello]" );
console.log( c );
c.EDIT_IN_PLACE_DOES_NOT_WORK("[World]");
console.log( c );
==================================================
after years (and ES6) … we have a new option how to do this:
Object.defineProperty( String.prototype, 'distance', {
value: function ( param )
{
// your code …
return 'counting distance between ' + this + ' and ' + param;
}
} );
// ... and use it like this:
const result = "a".distance( "b" );
console.log(result);
You could do this:
String.prototype.distance = function (){
//your code
}
Using prototype to add you own function to string is called a prototype I created small JavaScript code that can select elements and change its innerHTML
var dom; //you can replce this to be $ just like jQuery
dom = function(elm) {
if(typeof elm === "object") {
// already done example
//typeof document.getElementById('id') will be object
return [elm];
} else {
return document.querySelectorAll(elm);
}
} // Returns elements by all css selector eg
// .class #id id p id > p id ~ p in short any css selectors
Object.prototype.text = function(txt) { //object prototype as NodeList returned would be object or maybe displayed as [Object NodeList]
var i = 0; //loop through the elements
for(i; i < this.length; i++) {
this[i].innerHTML = txt;
}
// in this function this refers to object that this function is passed on
};
dom('.classh').text('Changed for elements with classh');
dom('#heading').text('Changed for elements with id heading'); //examples

Toggle query string variables

I've been banging my head over this.
Using jquery or javascript, how can I toggle variables & values and then rebuild the query string? For example, my starting URL is:
http://example.com?color=red&size=small,medium,large&shape=round
Then, if the user clicks a button labeled "red", I want to end up with:
http://example.com?size=small,medium,large&shape=round //color is removed
Then, if the user clicks "red" again, I want to end up with:
http://example.com?size=small,medium,large&shape=round&color=red //color is added back
Then, if the user clicks a button labeled "medium", I want to end up with:
http://example.com?size=small,large&shape=round&color=red //medium is removed from list
Then, if the user clicks the labeled "medium" again, I want to end up with:
http://example.com?size=small,large,medium&shape=round&color=red //medium added back
It doesn't really matter what order the variable are in; I've just been tacking them to the end.
function toggle(url, key, val) {
var out = [],
upd = '',
rm = "([&?])" + key + "=([^&]*?,)?" + val + "(,.*?)?(&.*?)?$",
ad = key + "=",
rmrplr = function(url, p1, p2, p3, p4) {
if (p2) {
if (p3) out.push(p1, key, '=', p2, p3.substr(1));
else out.push(p1, key, '=', p2.substr(0, p2.length - 1));
} else {
if (p3) out.push(p1, key, '=', p3.substr(1));
else out.push(p1);
}
if (p4) out.push(p4);
return out.join('').replace(/([&?])&/, '$1').replace(/[&?]$/, ''); //<!2
},
adrplr = function(s) {
return s + val + ',';
};
if ((upd = url.replace(new RegExp(rm), rmrplr)) != url) return upd;
if ((upd = url.replace(new RegExp(ad), adrplr)) != url) return upd;
return url + (/\?.+/.test(url) ? '&' : '?') + key + '=' + val; //<!1
}
params self described enough, hope this help.
!1: changed from ...? '&' : '' to ... ? '&' : '?'
!2: changed from .replace('?&','?')... to .replace(/([&?]&)/,'$1')...
http://jsfiddle.net/ycw7788/Abxj8/
I have written a function, which efficiently results in the expected behaviour, without use of any libraries or frameworks. A dynamic demo can be found at this fiddle: http://jsfiddle.net/w8D2G/1/
Documentation
Definitions:
The shown example values will be used at the Usage section, below
  -   Haystack - The string to search in (default = query string. e.g: ?size=small,medium)
  -   Needle - The key to search for. Example: size
  -   Value - The value to replace/add. Example: medium.
Usage (Example: input > output):
qs_replace(needle, value)
If value exists, remove: ?size=small,medium > ?size=small
If value not exists, add: ?size=small > size=small,medium
qs_replace(needle, options)     Object options. Recognised options:
findString. Returns true if the value exists, false otherwise.
add, remove or toggleString. Add/remove the given value to/from needle. If remove is used, and the value was the only value, needle is also removed. A value won't be added if it already exists.
ignorecaseIgnore case while looking for the search terms (needle, add, remove or find).
separatorSpecify a separator to separate values of needle. Default to comma (,).
Note :   A different value for String haystack can also be defined, by adding it as a first argument: qs_replace(haystack, needle, value) or qs_replace(haystack, needle, options)
Code (examples at bottom). Fiddle: http://jsfiddle.net/w8D2G/1/:
function qs_replace(haystack, needle, options) {
if(!haystack || !needle) return ""; // Without a haystack or needle.. Bye
else if(typeof needle == "object") {
options = needle;
needle = haystack;
haystack = location.search;
} else if(typeof options == "undefined") {
options = needle;
needle = haystack;
haystack = location.search;
}
if(typeof options == "string" && options != "") {
options = {remove: options};
var toggle = true;
} else if(typeof options != "object" || options === null) {
return haystack;
} else {
var toggle = !!options.toggle;
if (toggle) {
options.remove = options.toggle;
options.toggle = void 0;
}
}
var find = options.find,
add = options.add,
remove = options.remove || options.del, //declare remove
sep = options.sep || options.separator || ",", //Commas, by default
flags = (options.ignorecase ? "i" :"");
needle = encodeURIComponent(needle); //URL-encoding
var pattern = regexp_special_chars(needle);
pattern = "([?&])(" + pattern + ")(=|&|$)([^&]*)(&|$)";
pattern = new RegExp(pattern, flags);
var subquery_match = haystack.match(pattern);
var before = /\?/.test(haystack) ? "&" : "?"; //Use ? if not existent, otherwise &
var re_sep = regexp_special_chars(sep);
if (!add || find) { //add is not defined, or find is used
var original_remove = remove;
if (subquery_match) {
remove = encodeURIComponent(remove);
remove = regexp_special_chars(remove);
remove = "(^|" + re_sep + ")(" + remove + ")(" + re_sep + "|$)";
remove = new RegExp(remove, flags);
var fail = subquery_match[4].match(remove);
} else {
var fail = false;
}
if (!add && !fail && toggle) add = original_remove;
}
if(find) return !!subquery_match || fail;
if (add) { //add is a string, defined previously
add = encodeURIComponent(add);
if(subquery_match) {
var re_add = regexp_special_chars(add);
re_add = "(^|" + re_sep + ")(" + re_add + ")(?=" + re_sep + "|$)";
re_add = new RegExp(re_add, flags);
if (subquery_match && re_add.test(subquery_match[4])) {
return haystack;
}
if (subquery_match[3] != "=") {
subquery_match = "$1$2=" + add + "$4$5";
} else {
subquery_match = "$1$2=$4" + sep + add + "$5";
}
return haystack.replace(pattern, subquery_match);
} else {
return haystack + before + needle + "=" + add;
}
} else if(subquery_match){ // Remove part. We can only remove if a needle exist
if(subquery_match[3] != "="){
return haystack;
} else {
return haystack.replace(pattern, function(match, prefix, key, separator, value, trailing_sep){
// The whole match, example: &foo=bar,doo
// will be replaced by the return value of this function
var newValue = value.replace(remove, function(m, pre, bye, post){
return pre == sep && post == sep ? sep : pre == "?" ? "?" : "";
});
if(newValue) { //If the value has any content
return prefix + key + separator + newValue + trailing_sep;
} else {
return prefix == "?" ? "?" : trailing_sep; //No value, also remove needle
}
}); //End of haystack.replace
} //End of else if
} else {
return haystack;
}
// Convert string to RegExp-safe string
function regexp_special_chars(s){
return s.replace(/([[^$.|?*+(){}\\])/g, '\\$1');
}
}
Examples (Fiddle: http://jsfiddle.net/w8D2G/1/):
qs_replace('color', 'red'); //Toggle color=red
qs_replace('size', {add: 'medium'}); //Add `medium` if not exist to size
var starting_url = 'http://example.com?color=red&size=small,medium,large&shape=round'
starting_url = qs_replace(starting_url, 'color', 'red'); //Toggle red, thus remove
starting_url = qs_replace(starting_url, 'color', 'red'); //Toggle red, so add it
alert(starting_url);
This is the solution for your task: http://jsfiddle.net/mikhailov/QpjZ3/12/
var url = 'http://example.com?size=small,medium,large&shape=round';
var params = $.deparam.querystring(url);
var paramsResult = {};
var click1 = { size: 'small' };
var click2 = { size: 'xlarge' };
var click3 = { shape: 'round' };
var click4 = { shape: 'square' };
var clickNow = click4;
for (i in params) {
var clickKey = _.keys(clickNow)[0];
var clickVal = _.values(clickNow)[0];
if (i == clickKey) {
var ar = params[i].split(',');
if (_.include(ar, clickVal)) {
var newAr = _.difference(ar, [clickVal]);
} else {
var newAr = ar;
newAr.push(clickVal);
}
paramsResult[i] = newAr.join(',');
} else {
paramsResult[i] = params[i];
}
}
alert($.param(paramsResult)) // results see below
Init params string
{ size="small, medium,large", shape="round"} // size=small,medium,large&shape=round
Results
{ size="small"} => { size="medium,large", shape="round"} //size=medium%2Clarge&shape=round
{ size="xlarge"} => { size="small,medium,large,xlarge", shape="round"} // size=small%2Cmedium%2Clarge%2Cxlarge&shape=round
{ shape="round"} => { size="small,medium,large", shape=""} //size=small%2Cmedium%2Clarge&shape=
{ shape="square"} => { size="small,medium,large", shape="round,square"} //size=small%2Cmedium%2Clarge&shape=round%2Csquare
productOptions is the only thing you need to modify here to list all the available options and their default state. You only need to use the public API function toggleOption() to toggle an option.
(function(){
//Just keep an object with all the options with flags if they are enabled or disabled:
var productOptions = {
color: {
"red": true,
"blue": true,
"green": false
},
size: {
"small": true,
"medium": true,
"large": true
},
shape: {
"round": true
}
};
//After this constructing query becomes pretty simple even without framework functions:
function constructQuery(){
var key, opts, qs = [], enc = encodeURIComponent, opt,
optAr, i;
for( key in productOptions ) {
opts = productOptions[key];
optAr = [];
for( i in opts ) {
if( opts[i] ) {
optAr.push( i );
}
}
if( !optAr.length ) {
continue;
}
qs.push( enc( key ) + "=" + enc( optAr.join( "," ) ) );
}
return "?"+qs.join( "&" );
};
//To toggle a value and construct the new query, pass what you want to toggle to this function:
function toggleOption( optionType, option ) {
if( optionType in productOptions && option in productOptions[optionType] ) {
productOptions[optionType][option] = !productOptions[optionType][option];
}
return constructQuery();
}
window.toggleOption = toggleOption;
})()
Example use:
// "%2C" = url encoded version of ","
toggleOption(); //Default query returned:
"?color=red%2Cblue&size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "color", "red" ); //Red color removed:
"?color=blue&size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "color", "blue" ); //Blue color removed, no color options so color doesn't show up at all:
"?size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "color", "blue" ); //Blue color enabled again:
"?color=blue&size=small%2Cmedium%2Clarge&shape=round"
toggleOption( "shape", "round" ); //The only shape option removed
"?color=blue&size=small%2Cmedium%2Clarge"
I have tried this and this may give the desire result
<script>
var url='http://example.com?color=red&size=small,medium,large&shape=round';
var mySplitResult = url.split("?");
var domain=mySplitResult[0];
var qstring=mySplitResult[1];
var proparr=new Array();
var valarr=new Array();
var mySplitArr = qstring.split("&");
for (i=0;i<mySplitArr.length;i++){
var temp = mySplitArr[i].split("=");
proparr[i]=temp[0];
valarr[i]=temp[1].split(",");
}
function toggle(property,value)
{
var index;
var yes=0;
for (i=0;i<proparr.length;i++){
if(proparr[i]==property)
index=i;
}
if(index==undefined){
proparr[i]=property;
index=i;
valarr[index]=new Array();
}
for (i=0;i<valarr[index].length;i++){
if(valarr[index][i]==value){
valarr[index].splice(i,1);
yes=1;
}
}
if(!yes)
{
valarr[index][i]=value;
}
var furl=domain +'?';
var test=new Array();
for(i=0;i<proparr.length;i++)
{
if(valarr[i].length)
{
test[i]=valarr[i].join(",");
furl +=proparr[i]+"="+test[i]+"&";
}
}
furl=furl.substr(0,furl.length-1)
alert(furl);
}
</script>
<div>
<input id="color" type="button" value="Toggle Red" onclick="toggle('color','red')"/>
<input id="shape" type="button" value="Toggle shape" onclick="toggle('shape','round')"/>
<input id="size" type="button" value="Toggle Small" onclick="toggle('size','small')"/>
<input id="size" type="button" value="Toggle large" onclick="toggle('size','large')"/>
<input id="size" type="button" value="Toggle medium" onclick="toggle('size','medium')"/>
<input id="size" type="button" value="Toggle new" onclick="toggle('new','yes')"/>
</div>

Categories

Resources