Exempting characters in an escaped string - javascript

I have a little function that makes URL arguments out of an object:
function MkArgs(o) {
var ret = '?';
for (var i in o) {
ret += i + '=' + escape(o[i]) + '&';
}
return ret.substr(0, ret.length - 1);
}
which I then can call like this:
MkArgs({
protocol: 'wsfederation',
realm: 'https://www.x.com/',
fedRes: 'Home/FederationResult',
context: '~/Home/FAQ',
version: '1.0',
callback: '?'
});
to produce the following:
?protocol=wsfederation&realm=https%3A//www.x.com/&fedRes=Home/FederationResult&context=%7E/Home/FAQ&version=1.0&callback=%3F
everything is fine except that I don't want the last argument escaped i.e. I want:
callback=?
instead of
callback=%3F
is there any way I can indicate that within the string? I tried '\?' but that doesn't do it and haven't found any references as to how to protect a piece of string from escaping...
e

The MkArgs function is your own; change it to include an escape mechanism. I would advise against using backslash, though. If this is just your own code, perhaps it would be enough to put in a hackish special case.

That's a pretty special case. Maybe you should change your function:
function MkArgs(o, isJSONP) {
var ret = '?';
for (var i in o) {
var val = o[i];
val = escape(val);
ret += i + '=' + val + '&';
}
return ret.substr(0, ret.length - 1) + isJSONP ? '&callback=?':'';
}
and call it:
MkArgs({
protocol: 'wsfederation',
realm: 'https://www.x.com/',
fedRes: 'Home/FederationResult',
context: '~/Home/FAQ',
version: '1.0'
}, true);

The escape or encodeURIComponent functions don't have any way of "skipping" certain characters. So, all you can do is to either avoid calling the encode function when you don't want to or replace the chars you don't want encoded, call encode and then put the original chars back again.
If you want to skip escaping the whole value for a particular key, you can just check for the particular keys that you don't want to escape and handle appropriately like this:
function MkArgs(o) {
var ret = '?';
for (var i in o) {
var val = o[i];
if (i != "callback") {
val = encodeURIComponent(val);
}
ret += i + '=' + val + '&';
}
return ret.substr(0, ret.length - 1);
}
If you want to skip just certain characters, then you can replace them with some unique sequence, escape and then put them back:
function MkArgs(o) {
var ret = '?';
for (var i in o) {
var val = o[i];
if (i == "callback") {
val = val.replace(/\?/, "--xx--"); // replace with unique sequence
val = encodeURIComponent(val);
val = val.replace(/--xx--/, "?"); // put orig characters back
} else {
val = encodeURIComponent(val);
}
ret += i + '=' + val + '&';
}
return ret.substr(0, ret.length - 1);
}
FYI, note I've switched to using encodeURIComponent() which is recommended over the deprecated escape() because escape() doesn't work for non-ascii characters.

thanks everyone for the replies. what I ended up doing was:
function MkArgs(o) {
var ret = '?';
for (var i in o) {
ret += i;
if (o[i]) ret += '=' + escape(o[i]);
ret += '&';
}
return ret.substr(0, ret.length - 1);
}
then calling it like:
MkArgs({
protocol: 'wsfederation',
realm: 'https://www.x.com/',
fedRes: 'Home/FederationResult',
context: '~/Home/FAQ',
version: '1.0',
'callback=?': null
});
that way I don't rely on the values but the keys to make the distinction. not really pretty but it's the best I could think of

function MkArgs(o) {
var ret = '?';
var lastEl = '';
for (var i in o) {
ret += i + '=' + escape(o[i]) + '&';
lastEl = o[i];
}
return ret.substr(0, ret.length - 1 - lastEl.length) + lastEl;
}
this works for the last element in the object.
EDIT: It seems that in a classic for in loop, javascript does not have a precise order in which it loops over the object props, so the above solution is not guaranteed to work.
In this case you have 2 solutions :
If you know which property you want to "protect" from escaping, you should check for that prop in the loop and specifically not escape it :
for (var i in o) {
if(i=="myProp")
// unescape
else
// escape
}
If you do not now the property, but you want only the last one added into the query, you can do something like this (after building the query) :
var q = MkArgs(o);
var parts = q.split('=');
var toUnescape = parts[parts.length-1];
q = q.substring(0,q.length - toUnescape.length) + unescape(toUnescape);

Related

How can I split a string without losing the separator and without regex?

I have a string similar to "<p></p>". Now, I want to split this string, so I have 2 tags. If I do
var arr = "<p></p>".split("><") , I get an array that looks like
["<p", "/p>"]
Is there a simple way to keep the separator in this split? NOT a REGEX (Not a dupe) I want :
["<p>","</p>"]
Since javascript regex doesn't support look behind assertion it's not possible with String#split method. Use String#match method to get the complete string.
var arr = "<p></p>".match(/[\s\S]+?>(?=<|$)/g)
console.log(arr)
Without regex and using split you can do something like this.
var arr = "<p></p>".split('><').map(function(v, i, arr1) {
if (i != 0)
v = '<' + v;
if (i < arr1.length - 1)
v += '>';
return v;
})
// using ternary
var arr1 = "<p></p>".split('><').map(function(v, i, arr1) {
return (i != 0 ? '<' : '') + v + (i < arr1.length - 1 ? '>' : '');
})
console.log(arr);
console.log(arr1);
To do this without a regular expression, you'll need some kind of parser. Inspect every character, build up chunks and store them in an array. You may then want to process the bits, looking for tokens or doing other processing. E.g.
/* Break string into chunks of <...>, </...> and anything in between.
** #param {string} s - string to parse
** #returns {Array} chunks of string
*/
function getChunks(s) {
var parsed = [];
var limit = s.length - 1;
s.split('').reduce(function(buffer, char, i) {
var startTag = char == '<';
var endTag = char == '/';
var closeTag = char == '>';
if (startTag) {
if (buffer.length) {
parsed.push(buffer);
}
buffer = char;
} else if (endTag) {
buffer += char;
} else if (closeTag) {
parsed.push(buffer + char)
buffer = '';
} else {
buffer += char;
}
if (i == limit && buffer.length) {
parsed.push(buffer);
}
return buffer;
}, '');
return parsed;
}
['<p></p>',
'<div>More complex</div>',
'<span>broken tag</sp'
].forEach(function(s){
console.log(s + ' => [' + getChunks(s) + ']')
});
Note that this is very simple and just looks for <...> and </...> where ... can be anything.

How to get parameter value inside a string?

Here's a thing i've been trying to resolve...
We've got some data from an ajax call and the result data is between other stuff a huge string with key:value data. For example:
"2R=OK|2M=2 row(s) found|V1=1,2|"
Is it posible for js to do something like:
var value = someFunction(str, param);
so if i search for "V1" parameter it will return "1,2"
I got this running on Sql server no sweat, but i'm struggling with js to parse the string.
So far i'm able to do this by a VERY rudimentary for loop like this:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
var arr = str.split("|");
var i = 0;
var value = "";
for(i = 0; i<arr.length; ++i){
if( arr[i].indexOf(param)>-1 ){
value = arr[i].split("=")[1];
}
}
console.log(value);
if i put that into a function it works, but i wonder if there's a more efficient way to do it, maybe some regex? but i suck at it. Hopefully somebody may shine a light on this for me?
Thanks!
This seems to work for your specific use-case:
function getValueByKey(haystack, needle) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp(needle + '=(.+)');
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1');
console.log(test);
JS Fiddle demo.
And, to include the separator in your search (in order to prevent somethingElseV1 matching for V1):
function getValueByKey(haystack, needle, separator) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp('\\' + separator + needle + '=(.+)\\' + separator);
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1', '|');
console.log(test);
JS Fiddle demo.
Note that this approach does require the use of the new RegExp() constructor (rather than creating a regex-literal using /.../) in order to pass variables into the regular expression.
Similarly, because we're using a string to create the regular expression within the constructor, we need to double-escape characters that require escaping (escaping first within the string and then escaping within in the created RegExp).
References:
RegExp.
String.match().
This should work for you and it's delimiters are configurable (if you wish to parse a similar string with different delimiters, you can just pass in the delimiters as arguments):
var parseKeyValue = (function(){
return function(str, search, keyDelim, valueDelim){
keyDelim = quote(keyDelim || '|');
valueDelim = quote(valueDelim || '=');
var regexp = new RegExp('(?:^|' + keyDelim + ')' + quote(search) + valueDelim + '(.*?)(?:' + keyDelim + '|$)');
var result = regexp.exec(str);
if(result && result.length > 1)
return result[1];
};
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
})();
Quote function borrowed form this answer
Usage examples:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
parseKeyValue(str, param); // "1,2"
var str = "2R=OK&2M=2 row(s) found&V1=1,2";
var param = "2R";
parseKeyValue(str, param, '&'); // "OK"
var str =
"2R=>OK\n\
2M->2 row(s) found\n\
V1->1,2";
var param = "2M";
parseKeyValue(str, param, '\n', '->'); // "2 row(s) found"
Here is another approach:
HTML:
<div id="2R"></div>
<div id="2M"></div>
<div id="V1"></div>
Javascript:
function createDictionary(input) {
var splittedInput = input.split(/[=|]/),
kvpCount = Math.floor(splittedInput.length / 2),
i, key, value,
dictionary = {};
for (i = 0; i < kvpCount; i += 1) {
key = splittedInput[i * 2];
value = splittedInput[i * 2 + 1];
dictionary[key] = value;
}
return dictionary;
}
var input = "2R=OK|2M=2 row(s) found|V1=1,2|",
dictionary = createDictionary(input),
div2R = document.getElementById("2R"),
div2M = document.getElementById("2M"),
divV1 = document.getElementById("V1");
div2R.innerHTML = dictionary["2R"];
div2M.innerHTML = dictionary["2M"];
divV1.innerHTML = dictionary["V1"];
Result:
OK
2 row(s) found
1,2

Javascript Reg Expression to replace Get Parameter in the URL

Using a regular expression, I want to write a function that will take a URL and a parameter name: ReplaceParamValueinURL (url, param, value).
If the parameter exists, it will replace the value in the URL.
If the parameter doesn't exist, it will add it to the URL along with the value.
If the parameter exists with no value, it will add the value to the parameter.
Is there an elegant way of doing all three in regex find and replace?
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, a , 4)
returns http://google.com?a=4&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, a , 4)
returns http://google.com?a=4&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, c , 4)
returns http://google.com?a=1&b=2&c=4
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, d , 5)
returns http://google.com?a=1&b=2&c=3&d=5
ReplaceParamValueinURL ("http://google.com?aaa=0&a=1&b=2&c=3, a , 6)
returns http://google.com?aaa=0&a=6&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3, b , 2)
returns http://google.com?a=1&b=2&c=3
I am hoping to do this with Reg ex instead of split. I really appreciate it if you can explain your answer if the regex is too complex. Is there a jQuery function that already does this?
I guess it's a very common case but can have many corner cases.
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3#test, a , 2)
returns http://google.com?a=2&b&c=3#test
No you can't do it with a single regexp, but the function is pretty simple, i've tested it with all your examples so it should work:
function ReplaceParamValueinURL (url, name, val) {
//Try to replace the parameter if it's present in the url
var count = 0;
url = url.replace(new RegExp("([\\?&]" + name + "=)[^&]+"), function (a, match) {
count = 1;
return match + val;
});
//If The parameter is not present in the url append it
if (!count) {
url += (url.indexOf("?") >=0 ? "&" : "?") + name + "=" + val;
}
return url;
}
try this,
function ReplaceParamValueinURL(url , replceparam , replaceValue)
{
regExpression = "(\\?|&)"+replceparam+"(=).(&|)";
var regExpS = new RegExp(regExpression, "gm");
var getmatch = url.match(regExpS);
var regExpSEq = new RegExp("=", "g");
var getEqalpostion = regExpSEq.exec(getmatch);
var newValue;
if(getmatch[0].charAt(getmatch[0].length - 1) != "&")
{
var subSrtingToReplace = getmatch[0].substring((getEqalpostion.index+ 1),getmatch[0].length );
newValue = getmatch[0].replace(subSrtingToReplace , replaceValue);
}
else
{
var subSrtingToReplace = getmatch[0].substring((getEqalpostion.index+ 1) , getmatch[0].length - 1 );
newValue = getmatch[0].replace(subSrtingToReplace , replaceValue);
}
return returnString = url.replace(regExpS , newValue);
}

Convert JavaScript object into URI-encoded string

I got a JavaScript object which I would like to get x-www-form-urlencoded.
Something like $('#myform').serialize() but for objects.
The following object:
{
firstName: "Jonas",
lastName: "Gauffin"
}
would get encoded to:
firstName=Jonas&lastName=Gauffin (do note that special characters should get encoded properly)
I'm surprised that no one has mentioned URLSearchParams
var prms = new URLSearchParams({
firstName: "Jonas",
lastName: "Gauffin"
});
console.log(prms.toString());
// firstName=Jonas&lastName=Gauffin
Please look closely at both answers I provide here to determine which fits you best.
Answer 1:
Likely what you need: Readies a JSON to be used in a URL as a single argument, for later decoding.
jsfiddle
encodeURIComponent(JSON.stringify({"test1":"val1","test2":"val2"}))+"<div>");
Result:
%7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D
For those who just want a function to do it:
function jsonToURI(json){ return encodeURIComponent(JSON.stringify(json)); }
function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); }
Answer 2:
Uses a JSON as a source of key value pairs for x-www-form-urlencoded output.
jsfiddle
// This should probably only be used if all JSON elements are strings
function xwwwfurlenc(srcjson){
if(typeof srcjson !== "object")
if(typeof console !== "undefined"){
console.log("\"srcjson\" is not a JSON object");
return null;
}
u = encodeURIComponent;
var urljson = "";
var keys = Object.keys(srcjson);
for(var i=0; i <keys.length; i++){
urljson += u(keys[i]) + "=" + u(srcjson[keys[i]]);
if(i < (keys.length-1))urljson+="&";
}
return urljson;
}
// Will only decode as strings
// Without embedding extra information, there is no clean way to
// know what type of variable it was.
function dexwwwfurlenc(urljson){
var dstjson = {};
var ret;
var reg = /(?:^|&)(\w+)=(\w+)/g;
while((ret = reg.exec(urljson)) !== null){
dstjson[ret[1]] = ret[2];
}
return dstjson;
}
See jQuery.param(...). Converts to uri, see link for more information!
Since you were asking for a serialized object, this is probably slightly off the mark. But just in case, if your intent is to use the values within that object as individual parameters, this might be the conversion you're looking for:
var params = {
"param1": "arg1",
"param2": "arg2"
};
var query = "";
for (key in params) {
query += encodeURIComponent(key)+"="+encodeURIComponent(params[key])+"&";
}
xmlhttp.send(query);
Same as above in effect, but functional style gives an elegant expression::
const to_encoded = obj => Object.keys(obj).map(k =>
`${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
FYI, the accepted answer doesn't include support for nested objects. Here's one way that you can accomplish this:
function xwwwfurlenc(srcjson, parent=""){
if(typeof srcjson !== "object")
if(typeof console !== "undefined"){
console.log("\"srcjson\" is not a JSON object");
return null;
}
let u = encodeURIComponent;
let urljson = "";
let keys = Object.keys(srcjson);
for(let i=0; i < keys.length; i++){
let k = parent ? parent + "[" + keys[i] + "]" : keys[i];
if(typeof srcjson[keys[i]] !== "object"){
urljson += u(k) + "=" + u(srcjson[keys[i]]);
} else {
urljson += xwwwfurlenc(srcjson[keys[i]], k)
}
if(i < (keys.length-1))urljson+="&";
}
return urljson;
}
An extension to #Grallen's Answer 1 – if you need a shorter URL:
Input:
{"q":"SomethingTM","filters":[{"kind":"A","q":"foobar"},{"kind":"B","isntIt":true}],"pagenumber":1}
Output:
('q'~'SomethingTM'_'filters'~!('kind'~'A'_'q'~'foobar')_('kind'~'B'_'isntIt'~true)*_'pagenumber'~1)
Instead of:
%7B%22q%22%3A%22SomethingTM%22%2C%22filters%22%3A%5B%7B%22kind%22%3A%22A%22%2C%22q%22%3A%22foobar%22%7D%2C%7B%22kind%22%3A%22B%22%2C%22isntIt%22%3Atrue%7D%5D%2C%22pagenumber%22%3A1%7D
function jsonToUri(v, r, s) {
return encodeURIComponent(
JSON.stringify(v, r, s)
.replace(/[()'~_!*]/g, function(c) {
// Replace ()'~_!* with \u0000 escape sequences
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4)
})
.replace(/\{/g, '(') // { -> (
.replace(/\}/g, ')') // } -> )
.replace(/"/g, "'") // " -> '
.replace(/\:/g, '~') // : -> ~
.replace(/,/g, '_') // , -> _
.replace(/\[/g, '!') // [ -> !
.replace(/\]/g, '*') // ] -> *
)
}
function uriToJson(t, r) {
return JSON.parse(
decodeURIComponent(t)
.replace(/\(/g, '{') // ( -> {
.replace(/\)/g, '}') // ) -> }
.replace(/'/g, '"') // ' -> "
.replace(/~/g, ':') // ~ -> :
.replace(/_/g, ',') // _ -> ,
.replace(/\!/g, '[') // ! -> [
.replace(/\*/g, ']') // * -> ]
, r
)
}
//////// TESTS ////////
var a = {q: 'SomethingTM', filters: [{kind: 'A', q: 'foobar'}, {kind: 'B', isntIt: true}], pagenumber: 1}
var b = jsonToUri(a)
var c = uriToJson(b)
console.log(b)
// ('q'~'SomethingTM'_'filters'~!('kind'~'A'_'q'~'foobar')_('kind'~'B'_'isntIt'~true)*_'pagenumber'~1)
console.log(JSON.stringify(c))
// {"q":"SomethingTM","filters":[{"kind":"A","q":"foobar"},{"kind":"B","isntIt":true}],"pagenumber":1}
var a2 = {"q":"Something(TM)","filters":[{"kind":"A*","q":"foo_bar"},{"kind":"B!","isn'tIt":true}],"page~number":1}
var b2 = jsonToUri(a2)
var c2 = uriToJson(b2)
console.log(b2)
// ('q'~'Something%5Cu0028TM%5Cu0029'_'filters'~!('kind'~'A%5Cu002a'_'q'~'foo%5Cu005fbar')_('kind'~'B%5Cu0021'_'isn%5Cu0027tIt'~true)*_'page%5Cu007enumber'~1)
console.log(JSON.stringify(c2))
// {"q":"Something(TM)","filters":[{"kind":"A*","q":"foo_bar"},{"kind":"B!","isn'tIt":true}],"page~number":1}
To build on #Claymore's answer, Here is a function to encode an object and additionally omit the trailing ampersand:
encodeObject(params) {
var query = [];
for (let key in params) {
let val = encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
query.push(val);
}
return query.join('&');
}
function jsonToURI(jsonObj) {
var output = '';
var keys = Object.keys(jsonObj);
keys.forEach(function(key) {
output = output + key + '=' + jsonObj[key] + '&';
})
return output.slice(0, -1);
}
function uriToJSON(urijson) {
var output = {};
urijson = decodeURIComponent(urijson);
urijson = urijson.split('&');
urijson.forEach(function(param) {
var param = param.split('=');
output[param[0]] = param[1];
})
return output
}
let urlParameters = Object.entries(data).map(e => e.join('=')).join('&');
Try using this.
create a function to parse the query params.
const parseQueryParams = (query) => {
return Object.entries(query)
.map(([key, value]) => key + '=' + encodeURIComponent(value))
.join('&')
}
You need to use JSON.stringify() to serialize the JSON/JavaScript object.
It is natively available in almost all the modern browsers but you can include the below js which will add the required library incase it is not available.
http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

Search and replace specific query string parameter value in javascript

I have a string which is something like this :
a_href= "www.google.com/test_ref=abc";
I need to search for test_ref=abc in thisabove strinng and replace it with new value
var updated_test_ref = "xyz";
a_href ="www.google.com/test_ref=updated_test_ref"
i.e
www.google.com/test_ref=xyz.
How can we do this ?
EDIT:
test_ref value can be a URL link in itself something like http://google.com?param1=test1&param2=test2. I need to capture complete value not till first &.
a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);
Based on this discussion I have fixed the Chris function (problem with regex string!)
function updateUrlParameter(url, param, value){
var regex = new RegExp('('+param+'=)[^\&]+');
return url.replace( regex , '$1' + value);
}
Based on this discussion I have created a references function. enjoy
updateUrlParameter(url, param, value){
var regex = new RegExp("/([?|&]" + param + "=)[^\&]+/");
return url.replace(regex, '$1' + value);
}
I was searching for this solution for few hours and finally stumbled upon this question. I have tried all the solutions here. But there is still an issue while replacing specific param value in url.
Lets take a sample url like
http://google.com?param1=test1&param2=test2&anotherparam1=test3
and the updated url should be like
http://google.com?param1=newtest&param2=test2&anotherparam1=test3, where value of param1 is changed.
In this case, as #Panthro has pointed out, adding [?|&] before the querying string ensures that anotherparam1 is not replaced. But this solution also adds the '?' or '&' character to the matching string. So while replacing the matched characters, the '?' or '&' will also get replaced. You will not know exactly which character is replaced so you cannot append that character as well.
The solution is to match '?' or '&' as preceding characters only.
I have re-written the function of #Chris, fixing the issue with string and have added case insensitive argument.
updateUrlParameter(url, param, value){
var regex = new RegExp('(?<=[?|&])(' + param + '=)[^\&]+', 'i');
// return url.replace(regex, param + '=$1' + value);
return url.replace(regex, param + '=' + value);
}
Here (?<=[?|&]) means, the regex will match '?' or '&' char and will take the string that occurs after the specified character (looks behind the character). That means only param1=test1 substring will be matched and replaced.
I know this is a bit dirty code but I've achieved what I was looking for. It replaces the given query string or adds new one if it doesn't exist yet.
function updateUrlParameter(url, param, value) {
var index = url.indexOf("?");
if (index > 0) {
var u = url.substring(index + 1).split("&");
var params = new Array(u.length);
var p;
var found = false;
for (var i = 0; i < u.length; i++) {
params[i] = u[i].split("=");
if (params[i][0] === param) {
params[i][1] = value;
found = true;
}
}
if (!found) {
params.push(new Array(2));
params[params.length - 1][0] = param;
params[params.length - 1][1] = value;
}
var res = url.substring(0, index + 1) + params[0][0] + "=" + params[0][1];
for (var i = 1; i < params.length; i++) {
res += "&" + params[i][0] + "=" + params[i][1];
}
return res;
} else {
return url + "?" + param + "=" + value;
}
}
It will work when given regular URL addresses like:
updateUrlParameter('https://www.example.com/some.aspx?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/some.aspx','id','5');
Please note It will NOT work only if any of the query string parameter name or value contains "=" and/or "&" chars. It will work just fine behind that.
*Java script code to find a specific query string and replace its value *
('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});

Categories

Resources