Solved

How can I use jquery to parse out parameters from an encoded url with custom separators and place them into a string with pre-defined positions?

Posted on 2014-11-19
7
336 Views
Last Modified: 2014-11-22
My goal is to extract values from name-value pairs within a URL and return those values into a string that can be inserted into a web tracking tag.  Th using a js function. The string has fifteen positions separated by "-_-".  No matter where each name-value pair appears within the URL, values most always be inserted into the same position within the tracking tag string.  For example, the value(s) for the name apple must always appear in the first position, the value(s) for the name banana must always appear in the second position, and the value(s) for the name watermelon must always appear in the fifth position.

The URL will have a pound sign followed by an indefinite number of name-value pairs (up to 15). The name value pairs, connectors, and separators are encoded.  Values are strings that may be joined by "+" symbol.  Finally, Names may appear multiple times within the URL, each time with a different value.  However, since names only exactly one corresponding spot within the tracking tag string, the associated values must be joined into the same position (using "+").

Example URL:
http:www.mysite.com#currentPage=1&c%5B%5D=e%3A1119//e+apple//%3Aeq//red&c%5B%5D=e%3A1119//e+banana//%3Aeq//yellow+black&c%5B%5D=e%3A1119//e+watermelon//%3Aeq//red&c%5B%5D=e%3A1119//e+watermelon//%3Aeq//black

Example function using the tracking tag string created from above:
cmCreateElementTag("Tracking Parent", "Tracking Child","red-_-yellow+black-_--_--_-red+black-_--_--_--_--_--_--_--_--_--_-");

I'd like to use jquery to extract the values from the URL and place them in the right position within the tracking tag string.
0
Comment
Question by:JJ2357
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 43

Expert Comment

by:Rob
ID: 40456458
http://jsbin.com/bevivehaka/1/edit?js,console#J:L1

var myindex = {
	apple: 1,
	banana: 2,
	watermelon: 5
};
var myurl = "http://www.mysite.com#currentPage=1&c%5B%5D=e%3A1119//e+apple//%3Aeq//red&c%5B%5D=e%3A1119//e+banana//%3Aeq//yellow+black&c%5B%5D=e%3A1119//e+watermelon//%3Aeq//red&c%5B%5D=e%3A1119//e+watermelon//%3Aeq//black";

$(function() {
	var querystring = myurl.substring(myurl.indexOf('#')+1);
	var vars = decodeURIComponent(querystring).split('&');
	var results = {};
    for (var i = 1; i < vars.length; i++) {
        var pair = vars[i].split('=');
		var vals = pair[1].split('//');
		var fruit = vals[1].substring(2);
		var color = vals[3];
		if (results[fruit] === undefined) {
			results[fruit] = color;
		}
		else {
		  results[fruit] += "+" + color;
		}
    }
	console.dir(results);
	var tracking = Array.apply(null, new Array(15)).map(String.prototype.valueOf,"");
	$.each(results, function(i, el) {
		tracking[myindex[i]] = el;
	});
	console.log('cmCreateElementTag("Tracking Parent", "Tracking Child",'+tracking.join("-_-")+')');
});

function parseQueryString(query) {
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

Open in new window

0
 

Author Comment

by:JJ2357
ID: 40457112
Thanks, Rob.  Works great, with the exception of prepending "-_-" to the beginning of the string and not including double quotes around the string.  
Result:
 -_-red-_-yellow+black-_--_--_-red+black-_--_--_--_--_--_--_--_--_-

Open in new window

Expected result:
"red-_-yellow+black-_--_--_-red+black-_--_--_--_--_--_--_--_--_-"

Open in new window


Additionally, in the event that the URL contains an unencoded name-value pair, the function fails.  For example, if you append &name=value to the end, an undefined error is returned.
0
 
LVL 43

Expert Comment

by:Rob
ID: 40458565
Ok i've updated the code as the index was out by 1 (zero based array - first element is at index 0) http://jsbin.com/xukaso/1/edit?js,console#J:L1

As for the additional variables in the querystring, given that they weren't in your original spec, I haven't accounted for them.  So What are the variables that need to be parsed?  Will they always be the c[] variable or ?
0
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 
LVL 43

Accepted Solution

by:
Rob earned 500 total points
ID: 40458587
I've modified it so that all other variables are parsed into "otherVars" object whilst the array variables are parsed into the required string (http://jsbin.com/xukaso/1/edit?js,console)

var myindex = {
	apple: 0,
	banana: 1,
	watermelon: 4
};
var myurl = "http://www.mysite.com#currentPage=1&c%5B%5D=e%3A1119//e+apple//%3Aeq//red&c%5B%5D=e%3A1119//e+banana//%3Aeq//yellow+black&c%5B%5D=e%3A1119//e+watermelon//%3Aeq//red&c%5B%5D=e%3A1119//e+watermelon//%3Aeq//black&othervar=12345";

$(function() {
	var querystring = myurl.substring(myurl.indexOf('#')+1);
	var vars = decodeURIComponent(querystring).split('&');
	var results = {};
	var otherVars = {};
	// loop through the variables found
	for (var i = 0; i < vars.length; i++) {
		// find each pair of name/values
		var pair = vars[i].split('=');
		// we only want the "array" variables
		if (pair[0].indexOf('[]') > 0) {
			// each value is separated by //
			var vals = pair[1].split('//');
			// fruit and color found as below
			var fruit = vals[1].substring(2);
			var color = vals[3];
			// initialise the object with the color
			if (results[fruit] === undefined) {
				results[fruit] = color;
			}
			else {
				// If the fruit has already been found, add the corresponding color to the already existing value
				results[fruit] += "+" + color;
			}
		}
		else {
			// record all the other querystring variables here
			otherVars[pair[0]] = pair[1];
		}
	}
	// output the results
	console.dir(results);
	// output the other variables
	console.dir(otherVars);

	// now the cmCreateElementTag
	// create an array of 15 empty string values
	var tracking = Array.apply(null, new Array(15)).map(String.prototype.valueOf,"");
	// loop through this new array and assign the corresponding index retrieved from the myindex object
	$.each(results, function(i, el) {
		tracking[myindex[i]] = el;
	});
	// join the array as a string, serarated by -_- and output in the corresponding format
	console.log('cmCreateElementTag("Tracking Parent", "Tracking Child",'+tracking.join("-_-")+')');
});

Open in new window

0
 

Author Comment

by:JJ2357
ID: 40459478
works like a charm, tx.
0
 
LVL 43

Expert Comment

by:Rob
ID: 40459907
not a problem.  Sounds like that's solved it for you.  If so, go ahead and close the question: http://support.experts-exchange.com/customer/portal/articles/608621
0
 

Author Closing Comment

by:JJ2357
ID: 40459949
Sorry for not being clear in the original.  Thanks for the extra work.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Powershell- Registry HIVE 6 63
JQuery & Classic ASP 10 39
Make New Browser Window Fully Functional 7 35
Convert complicated date to yyyy-mm-dd format 22 49
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the pr…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question