JavaScript - Improve the URL parameter fetching algorithm - javascript

I need to get the URL search paramentes in an object, for eg; http://example.com/?a=x&b=y&d#pqr should yield {a:x, b:y, d:1}
Below is the method i used to get this, How can i improve this? any suggessions...
var urlParamKeyVals = new Array();
var pieces = new Array();
var UrlParams = {};
if(window.location.search.length){
var urlSearchString = window.location.search;
if(urlSearchString.charAt(0) == '?'){
urlSearchString = urlSearchString.substr(1);
urlParamKeyVals = urlSearchString.split("&");
}
}
for (var i = 0; i<urlParamKeyVals .length; i++) {
pieces = urlParamKeyVals [i].split("=");
if(pieces.length==1){
UrlParams[pieces[0]]=1;
} else {
UrlParams[pieces[0]]=pieces[1];
}
}
UrlParams;

I've made some time ago a small function for the same purpose:
Edit: To handle empty keys as 1:
function getQueryStringValues (str) {
str = str || window.location.search;
var result = {};
str.replace(/([^?=&]+)(?:[&#]|=([^&#]*))/g, function (match, key, value) {
result[key] = value || 1;
});
return result;
}
getQueryStringValues("http://example.com/?a=x&b=c&d#pqr");
// returns { a="x", b="c", d=1 }

function getParams(q){
var p, reg = /[?&]([^=#&]+)(?:=([^&#]*))?/g, params = {};
while(p = reg.exec(q)){
params[decodeURIComponent(p[1])] = p[2] ? decodeURIComponent(p[2]) : 1;
}
return params;
}
getParams(location.search);
-- edit
I extended the regular expression to match also the &param (no value) and &param= (empty value) cases. In both cases the value 1 is returned. It should also stop extracting on hash (#) character. Decoding values also supported.

jQuery bbq has a nice deparam method if you are trying to look at some very stable code:
http://github.com/cowboy/jquery-bbq/
http://benalman.com/code/projects/jquery-bbq/examples/deparam/

function getObjectFromSearch() {
var search = location.search;
var searchTerms = [];
var obj = {};
if (search !== '') {
search = search.replace(/^\?/,'');
searchTerms = search.split("&");
}
for (var i=0, imax=searchTerms.length; i<imax; i++) {
var ary = searchTerms[i].split("=");
obj[ary[0]] = ary[1];
}
return obj;
}

Related

multiple search pattern from string

I have this code below to search for a string of search string_search_* matched.
I'm wondering if there's any easier way to do this like maybe add multiple search term in indexof? is that possible?
My goal: just add variable string:
string_search4, 5, 6 and so on..
string = "this is a .bigcommerce.com site";
var string_search1 = 'cdn.shopify.com/s';
var string_search2 = '.bigcommerce.com/';
var string_search3 = 'woocommerce/';
// start checkig with SHOPIFY first
var s = string.indexOf(string_search1 );
var found_s = String(s);
// IF FOUND - look for the full url hubspot - like the mp4 url
if (found_s != '-1') {
var result = 'SHOPIFY'
return result;
}
// if NOT FOUND, check with BIGCOMMERCE
else {
var b = html.indexOf(string_search2);
var found_b = String(b);
if (found_b != '-1') {
var result = 'BIGCOMMERCE'
return result;
}
else {
var w = html.indexOf(string_search3);
var found_w = String(w);
if (found_w != '-1') {
var result = 'WOO COMMERCE'
return result;
}
else {
var result = 'CANNOT INDENTIFY CMS'
return result
}
}
}
This may look a little long, but is very expandable.
// Our "key" object and defaults
var sObj = function(id){
this.id = id;
this.found = false;
};
// Our self-contained object with search and result
// functions. This is were and how we can expand quickly
var s = {
'ob': [],
'find': function(haystack) {
if (this.ob) {
for(var x in this.ob) {
this.ob[x].found = (haystack.indexOf(this.ob[x].id) > -1);
}
}
},
'result': function() {
var r = "";
if (this.ob) {
for(var x in this.ob) {
if (this.ob[x].found) {
r += ","+this.ob[x].id;
}
}
}
return (r == "") ? r : r.substr(1);
}
};
// Create the object array with the "id"
// Add as many as you want.
s.ob.push(new sObj('shopify.com'));
s.ob.push(new sObj('bigcommerce.com'));
s.ob.push(new sObj('woocommerce.com'));
// quick debug for testing
//for(var x in s.ob) {
// console.log('x:['+ x +']['+ s.ob[x].id +']['+ s.ob[x].found +']');
//}
// Our string to be tested
var data = "this is a .bigcommerce.com site";
// check if the data matches one of the sObj ids
s.find(data);
// get the results
console.log('result:['+ s.result() +']');
// And for a second test (2 results)
data = "can you shopify.com or woocommerce.com me?";
s.find(data);
console.log('result:['+ s.result() +']');

Build object in JavaScript from PHP form input name

There are a couple of similar questions but none covers the case when a string looks like some-name[][some-key]. I have tried JSON.parse('some-name[][some-key]'); but it doesn't parse it.
Is there a way to convert such string to a JavaScript object that will look like { 'some-name': { 0: { 'some-key': '' } } }?
This is a name of a form field. It's normally parsed by PHP but I'd like to parse it with JavaScript the same way. I basically have <input name="some-name[][some-key]"> and I'd like to convert that to var something = { 'some-name': { 0: { 'some-key': VALUE-OF-THIS-FIELD } } }.
Try this:
JSON.parse('{ "some-name": [ { "some-key": "" } ] }');
I don't know exactly how you're doing this, but assuming they are all that format (name[][key]) and you need to do them one by one - this works for me:
var fieldObj = {};
function parseFieldName(nameStr)
{
var parts = nameStr.match(/[^[\]]+/g);
var name = parts[0];
var key = typeof parts[parts.length-1] != 'undefined' ? parts[parts.length-1] : false;
if(key===false) return false;
else
{
if(!fieldObj.hasOwnProperty(name)) fieldObj[name] = [];
var o = {};
o[key] = 'val';
fieldObj[name].push(o);
}
}
parseFieldName('some-name[][some-key]');
parseFieldName('some-name[][some-key2]');
parseFieldName('some-name2[][some-key]');
console.log(fieldObj); //Firebug shows: Object { some-name=[2], some-name2=[1]} -- stringified: {"some-name":[{"some-key":"val"},{"some-key2":"val"}],"some-name2":[{"some-key":"val"}]}
o[key] = 'val'; could of course be changed to o[key] = $("[name="+nameStr+"]").val() or however you want to deal with it.
Try this:
var input = …,
something = {};
var names = input.name.match(/^[^[\]]*|[^[\]]*(?=\])/g);
for (var o=something, i=0; i<names.length-1; i++) {
if (names[i])
o = o[names[i]] || (o[names[i]] = names[i+1] ? {} : []);
else
o.push(o = names[i+1] ? {} : []);
}
if (names[i])
o[names[i]] = input.value;
else
o.push(input.value);
Edit: according to your updated example, you can make something like this (view below). This will work - but only with the current example.
var convertor = function(element) {
var elementName = element.getAttribute('name');
var inpIndex = elementName.substring(0, elementName.indexOf('[')),
keyIndex = elementName.substring(elementName.lastIndexOf('[') + 1, elementName.lastIndexOf(']'));
var strToObj = "var x = {'" + inpIndex + "': [{'" + keyIndex + "': '" + element.value + "'}]}";
eval(strToObj);
return x;
};
var myObject = convertor(document.getElementById('yourInputID'));
Example here: http://paulrad.com/stackoverflow/string-to-array-object.html
(result is visible in the console.log)
old response
Use eval.. but your string must have a valid javascript syntax
So:
var str = "arr[][123] = 'toto'";
eval(str);
console.log(arr);
Will return a syntax error
Valid syntax will be:
var str = "var arr = []; arr[123] = 'toto'";
var x = eval(str);
console.log(arr);

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

get regex pattern for current URL

I have a url like this:
http://mysite.aspx/results.aspx?s=bcs_locations&k="Hospital" OR "Office" OR...
The terms after k= are coming from checkboxes, when checked the checkboxes values are being passed. Now I need to get the current URL and get all the values after k, so if there are two 'Hospital' and Office then grab those values and make the checkboxes with those values checked.. Trying hard to persist the checked checkboxes coz on refresh, all the checked checkboxes loose their state..
Hospitals<input name="LocType" type="checkbox" value="Hospital"/>  
Offices<input name="LocType" type="checkbox" value="Office"/>  
Emergency Centers<input name="LocType" type="checkbox" value="Emergency"/>
What I have so far is:
I want the regular expression for such URl pattern..can someone help?
var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop("checked", true);
}
This is what we use to grab info from the query string. It's from another S.O. answer that I can't find. But this will give you an object which represents all the options in the query string.
var qs = function(){
var query_string = {};
if(window.location.search){
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
}());
}
return query_string;
};
You could do it like this:
var MyApp = {
urlArgs:{}
};
MyApp.processUrlArgs = function() {
this.urlArgs = {};
var str = window.location.search ? window.location.search.substring(1) : false;
if( ! str ) return;
var sp = str.split(/&+/);
var rx = /^([^=]+)(=(.+))?/;
var k, v, i, m;
for( i in sp ) {
m = rx.exec( sp[i] );
if( ! m ) continue;
this.urlArgs[decodeURIComponent(m[1])] = decodeURIComponent(m[3]);
}
};
But what I don't understand is why do it like this? If you work in asp why don't you use HttpUtility.ParseQueryString?
try this
function getParamsFromUrl(url){
var paramsStr = url.split('?')[1],
params = paramsStr.split('&'),
paramsObj = {};
for(var i=0;i < params.length; i++){
var param= params[i].split('='),
name = param[0],
value = param[1];
paramsObj[name] = value;
}
return paramsObj;
}
var testUrl = 'http://mysite.aspx/results.aspx?s=bcs_locations&k=Hospital';
getParamsFromUrl(testUrl);//return: Object { s="bcs_locations", k="Hospital"}

Splitting a string only when the delimeter is not enclosed in quotation marks

I need to write a split function in JavaScript that splits a string into an array, on a comma...but the comma must not be enclosed in quotation marks (' and ").
Here are three examples and how the result (an array) should be:
"peanut, butter, jelly"
-> ["peanut", "butter", "jelly"]
"peanut, 'butter, bread', 'jelly'"
-> ["peanut", "butter, bread", "jelly"]
'peanut, "butter, bread", "jelly"'
-> ["peanut", 'butter, bread', "jelly"]
The reason I cannot use JavaScript's split method is because it also splits when the delimiter is enclosed in quotation marks.
How can I accomplish this, maybe with a regular expression ?
As regards the context, I will be using this to split the arguments passed from the third element of the third argument passed to the function you create when extending the jQuery's $.expr[':']. Normally, the name given to this parameter is called meta, which is an array that contains certain info about the filter.
Anyways, the third element of this array is a string which contains the parameters that are passed with the filter; and since the parameters in a string format, I need to be able to split them correctly for parsing.
What you are asking for is essentially a Javascript CSV parser. Do a Google search on "Javascript CSV Parser" and you'll get lots of hits, many with complete scripts. See also Javascript code to parse CSV data
Well, I already have a jackhammer of a solution written (general code written for something else), so just for kicks . . .
function Lexer () {
this.setIndex = false;
this.useNew = false;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments [i];
if (arg === Lexer.USE_NEW) {
this.useNew = true;
}
else if (arg === Lexer.SET_INDEX) {
this.setIndex = Lexer.DEFAULT_INDEX;
}
else if (arg instanceof Lexer.SET_INDEX) {
this.setIndex = arg.indexProp;
}
}
this.rules = [];
this.errorLexeme = null;
}
Lexer.NULL_LEXEME = {};
Lexer.ERROR_LEXEME = {
toString: function () {
return "[object Lexer.ERROR_LEXEME]";
}
};
Lexer.DEFAULT_INDEX = "index";
Lexer.USE_NEW = {};
Lexer.SET_INDEX = function (indexProp) {
if ( !(this instanceof arguments.callee)) {
return new arguments.callee.apply (this, arguments);
}
if (indexProp === undefined) {
indexProp = Lexer.DEFAULT_INDEX;
}
this.indexProp = indexProp;
};
(function () {
var New = (function () {
var fs = [];
return function () {
var f = fs [arguments.length];
if (f) {
return f.apply (this, arguments);
}
var argStrs = [];
for (var i = 0; i < arguments.length; ++i) {
argStrs.push ("a[" + i + "]");
}
f = new Function ("var a=arguments;return new this(" + argStrs.join () + ");");
if (arguments.length < 100) {
fs [arguments.length] = f;
}
return f.apply (this, arguments);
};
}) ();
var flagMap = [
["global", "g"]
, ["ignoreCase", "i"]
, ["multiline", "m"]
, ["sticky", "y"]
];
function getFlags (regex) {
var flags = "";
for (var i = 0; i < flagMap.length; ++i) {
if (regex [flagMap [i] [0]]) {
flags += flagMap [i] [1];
}
}
return flags;
}
function not (x) {
return function (y) {
return x !== y;
};
}
function Rule (regex, lexeme) {
if (!regex.global) {
var flags = "g" + getFlags (regex);
regex = new RegExp (regex.source, flags);
}
this.regex = regex;
this.lexeme = lexeme;
}
Lexer.prototype = {
constructor: Lexer
, addRule: function (regex, lexeme) {
var rule = new Rule (regex, lexeme);
this.rules.push (rule);
}
, setErrorLexeme: function (lexeme) {
this.errorLexeme = lexeme;
}
, runLexeme: function (lexeme, exec) {
if (typeof lexeme !== "function") {
return lexeme;
}
var args = exec.concat (exec.index, exec.input);
if (this.useNew) {
return New.apply (lexeme, args);
}
return lexeme.apply (null, args);
}
, lex: function (str) {
var index = 0;
var lexemes = [];
if (this.setIndex) {
lexemes.push = function () {
for (var i = 0; i < arguments.length; ++i) {
if (arguments [i]) {
arguments [i] [this.setIndex] = index;
}
}
return Array.prototype.push.apply (this, arguments);
};
}
while (index < str.length) {
var bestExec = null;
var bestRule = null;
for (var i = 0; i < this.rules.length; ++i) {
var rule = this.rules [i];
rule.regex.lastIndex = index;
var exec = rule.regex.exec (str);
if (exec) {
var doUpdate = !bestExec
|| (exec.index < bestExec.index)
|| (exec.index === bestExec.index && exec [0].length > bestExec [0].length)
;
if (doUpdate) {
bestExec = exec;
bestRule = rule;
}
}
}
if (!bestExec) {
if (this.errorLexeme) {
lexemes.push (this.errorLexeme);
return lexemes.filter (not (Lexer.NULL_LEXEME));
}
++index;
}
else {
if (this.errorLexeme && index !== bestExec.index) {
lexemes.push (this.errorLexeme);
}
var lexeme = this.runLexeme (bestRule.lexeme, bestExec);
lexemes.push (lexeme);
}
index = bestRule.regex.lastIndex;
}
return lexemes.filter (not (Lexer.NULL_LEXEME));
}
};
}) ();
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun) {
var len = this.length >>> 0;
var res = [];
var thisp = arguments [1];
for (var i = 0; i < len; ++i) {
if (i in this) {
var val = this [i];
if (fun.call (thisp, val, i, this)) {
res.push (val);
}
}
}
return res;
};
}
Now to use the code for your problem:
function trim (str) {
str = str.replace (/^\s+/, "");
str = str.replace (/\s+$/, "");
return str;
}
var splitter = new Lexer ();
splitter.setErrorLexeme (Lexer.ERROR_LEXEME);
splitter.addRule (/[^,"]*"[^"]*"[^,"]*/g, trim);
splitter.addRule (/[^,']*'[^']*'[^,']*/g, trim);
splitter.addRule (/[^,"']+/g, trim);
splitter.addRule (/,/g, Lexer.NULL_LEXEME);
var strs = [
"peanut, butter, jelly"
, "peanut, 'butter, bread', 'jelly'"
, 'peanut, "butter, bread", "jelly"'
];
// NOTE: I'm lazy here, so I'm using Array.prototype.map,
// which isn't supported in all browsers.
var splitStrs = strs.map (function (str) {
return splitter.lex (str);
});
var str = 'text, foo, "haha, dude", bar';
var fragments = str.match(/[a-z]+|(['"]).*?\1/g);
Even better (supports escaped " or ' inside the strings):
var str = 'text_123 space, foo, "text, here\", dude", bar, \'one, two\', blob';
var fragments = str.match(/[^"', ][^"',]+[^"', ]|(["'])(?:[^\1\\\\]|\\\\.)*\1/g);
// Result:
0: text_123 space
1: foo
2: "text, here\", dude"
3: bar
4: 'one, two'
5: blob
If you can control the input to enforce that the string will be enclosed in double-quotes " and that all elements withing the string will be enclosed in single-quotes ', and that no element can CONTAIN a single-quote, then you can split on , '. If you CAN'T control the input, then using a regular expression to sort/filter/split the input would be about as useful as using a regular expression to match against xhtml (see: RegEx match open tags except XHTML self-contained tags)

Categories

Resources