javascript, exception for string/object manipulation - javascript

So, I have to functions to turn a string to an object and an object to a string, however I need to account for an except and I am not sure how. Let me show you what I have
parseObjectToUrl: function (obj){
var myStr = "";
var first_iteration = true;
for (var p in obj) {
if(first_iteration){
myStr += p + "=";
first_iteration = false;
}else{
myStr += "&" + p + "=";
}
tObj = obj[p];
var first_inner = true;
for(t in tObj){
if(first_inner){
myStr += t;
first_inner = false;
}else{
myStr += "," + t;
}
yObj = tObj[t];
for( y in yObj){
myStr += "/" + yObj[y];
}
}
}
return myStr;
},
parseObjectFromUrl : function(url){
var builtObj = {};
//remove first slash
url = url.slice(0, 0) + url.slice(1);
var ch = url.split('&');
var tempParent = {};
for (var p in ch) {
var tempSub = {};
var arr = ch[p].split('=');
var keyParent = arr[0];
var splitInside = arr[1].split(",");
for (var i in splitInside) {
var sub = splitInside[i].split('/');
var subKey = sub[0];
tempSub[subKey] = sub.slice(1);
}
tempParent[keyParent] = tempSub;
}
return tempParent
}
So these the string looks like
/module1=mod1/2/3/4,mod2/2/3/4&module2=mod2/3/4/5
and the object looks like
myObj =
{
module1 : { mod1 : [2,3,4] , mod2 [2,3,4]} ,
module2 : { mod2 : [3,4,5]}
}
So these functions work fine for me however I (unfortunately) need to be able to handle the case when the user adds an "/" into the options like -
myObj =
{
module1 : { mod1 : [2/,3/,4/] , mod2 [2,3,4]} ,
module2 : { mod2 : [3,4,5]}
}
I'm sure it's going to throw a wrench in my function because i'm splitting by the "/", so I'm not sure how to get around this. Would i escape the slash? How would that fit into the functions if so? Looking for any advice on this issue. Thanks!
Edit:
I was able to encode the escaped url like :
obj.replace(/([/-])/g, "%2F");
to an escaped url, hoever I am having trouble doing the reverse of this. here is my attempt.
obj.replace(/(%2F)/g, "/");

in my opinion it would be better to use url arrays, but keep in mind the characters for your url could be limited:
maximum length of HTTP GET request?
having said that one could do something like this:
module1[]=1&module1[]=2&module2[]=4&module2[]=3
this is equal to the following pseudo code:
$_GET["module1"] = array(1,2);
$_GET["module2"] = array(4,3);
and use encodeURIComponent & decodeURIComponent for your values
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Related

How do I make the right conditions for the url based on the value of a variable? (javascript)

My script javascript like this :
<script>
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
if(sessionBrand)
var brand = '?brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = '&model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = '&category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = '&keyword='+this.sessionKeyword;
else
var keyword = '';
var newUrl = url+brand+model+category+keyword;
console.log(newUrl);
</script>
The result of console.log like this :
http://my-app.test/item?brand=honda&model=jazz&category=velg&keyword=RS 175/60 R 15
var sessionBrand, sessionModel, sessionCategory and sessionKeyword is dynamic. It can change. It can be null or it can have value
I have a problem
For example the case like this :
var sessionBrand = '';
var sessionModel = '';
var sessionCategory = '';
var sessionKeyword = 'RS 175/60 R 15';
The url to be like this :
http://my-app.test/item&keyword=RS 175/60 R 15
Should the url like this :
http://my-app.test/item?keyword=RS 175/60 R 15
I'm still confused to make the condition
How can I solve this problem?
Just use the array for params and then join them with & separator. For example:
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
var params = [];
if (sessionBrand) {
params.push('brand=' + sessionBrand);
}
if (sessionModel) {
params.push('model=' + sessionModel);
}
if(sessionCategory) {
params.push('category=' + sessionCategory);
}
if(sessionKeyword) {
params.push('category=' + sessionCategory);
}
var newUrl = url + '?' + params.join('&');
console.log(newUrl);
The problem with your code is that it is prefacing all query parameters with a & - except for the sessionBrand. What you need in a URL is for the first parameter to start with a ?, and all others with a &. As you saw, your code doesn't do this when there is no sessionBrand.
There are number of ways to fix this. Probably the neatest I can think of is to assemble the various parts as you are, but without any prefixes - then join them all together at the end. Like this (I just saw Viktor's solution, it's exactly the same idea, but neater because he rewrote more of your earlier code):
if(sessionBrand)
var brand = 'brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = 'model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = 'category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = 'keyword='+this.sessionKeyword;
else
var keyword = '';
var queryString = '?' + [sessionBrand, sessionModel, sessionCategory, sessionKeyword].filter(function(str) {
return str.length > 0;
}).join("&");
var newUrl = url+queryString;

How to use special characters in JSON stringify?

I am trying to stringify my json code for sending it to MVC controller.
But it does not work when data contains some special characters like greater than > or less than sign <.
Here is Sample code
function demo()
{
debugger
var demo = [];
demo.one = 'one';
demo.two = '<just>'
var treeBinding = JSON.stringify(demo);
$.ajax({
url: '/flow/demo',
type: "GET",
data: { dd: treeBinding },
success: function (res) {
},
error: function (error) {
alert(error)
}
});
}
JSON.stringify returns a blank array in this case.
Can anyone help me to get it worked?
First of all your declaration with array is incorrect.That is supposed to be an object but whatever case you need to check difference between object and array.However I assume that demo is an object with two key/properties which will be sent to server.
So declaration should look like this-
var demo = {};
demo.one = 'one';
demo.two = '<just>';
Then you should use to escape -
var treeBinding = encodeURIComponent(JSON.stringify(demo));
You can try something like this:
function arrayToObjectString(arr) {
var returnSrt = "{";
for (var key in arr) {
returnSrt += "\"" + key + "\" : \"" + arr[key] + "\"";
returnSrt += ","
}
returnSrt = returnSrt.substring(0, returnSrt.length - 1) + "}";
return returnSrt;
}
function main() {
var demo = [];
demo.one = 'one';
demo.two = '<just>'
console.log(JSON.stringify(demo))
var resultStr = arrayToObjectString(demo);
console.log(resultStr)
console.log(JSON.parse(resultStr));
}
main();

Javascript location.search

How could I specifically get every of these query strings in
file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000
For example, I want to get Testfirst, and then assign it to a variable so I can use it later on. Same thing with the others.
This is what I have so far to remove all the +, =
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&|(\/\?)/g,"\", \""))+"\"}")
I made that one for a webpage that uses a rare ("/?") separator too.
http://example.com/?a=0&b=bee/?c=third
First one will work for URLs like that
If you want it for a conventional location:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&/g,"\", \""))+"\"}")
Once splitSearch is defined you can get "pnum" string like this:
splitSearch.pnum
splitSearch["pnum"]
Another way to get it:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/(\=)|(\&)|(\/\?)/g, function(k) {
var rtn=k;
if (k == "\=") rtn="\"\:\"";
else if ((k == "\&") /*|| (k == "\/\?")*/) rtn="\",\"";
return rtn;
})+"\"}"))
A mix of use of replace with regEx and the split function does the work.
var str = "file:///K:/CKaing_C20_A01_Casino2/game.html?
First+Name=Testfirst&Last+Name=Testlast
&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000";
var argStrIndex = str.indexOf("?");
var argStr = str.substring(argStrIndex+1);
var args = argStr.replace(/\+/g," ").split("&");
for (var i=0;i<args.length;i++){
alert(args[i]);
}
demo: http://jsfiddle.net/7meAv/
something like that :
var search = location.search
.replace(/^\?/,'')
.replace(/\+/g,' ')
.split('&')
.map(function(string){
var split = string.split('=');
var res={};
res[split[0]]=split[1];
return res;
});
should return
[{"First Name":"Testfirst"},{"Last Name":"Testlast"},{"pnum":"123-456-7890"},{"postCode":"A1A 1A1"},{"startMoney":"5000"}]"
You'd need to take care of url encoding though.
A combination of the two answers already given (jsfiddle: http://jsfiddle.net/russianator/GymEq/)
var url = 'file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000';
queryObject = {};
url.substring(url.indexOf('?')+1)
.replace(/\+/g,' ')
.split('&')
.forEach(function(item) {
splitItem = item.split('=');
queryObject[splitItem[0]] = splitItem[1];
});
Returns an object like this:
{
"First Name": "Testfirst",
"Last Name": "Testlast",
...
}

How to get an url contained in query string

I want a javascript variable to be what is behind the ?url= in the url..
for example: The current url is
http://mywebsite.com/test/index.html?url=http://www.google.com/
So the variable has to be http://www.google.com/ .
I tried this, but it doesn't work… why ?
var url = document.URL ;
var appname = url.match(?url=(.+))[1];
Thanks.
I think the following will work for you:
function querystring(key) {
var query = window.location.search.substring(1);
var keys = query.split("&");
for (i = 0; i < keys.length; i++) {
var values = keys[i].split("=");
if (values[0] == key) {
return values[1];
}
}
}
var appname = querystring("url");
alert(appname);
Try this:
var regex = /\?url\=(.+)/;
var appname = regex.exec(url)[1];
or even simpler:
var appname = /\?url\=(.+)/.exec(url)[1];
var url = location.search.match(/url=([^&]+)&*.*$/)[1]; // http://www.google.com/
location //location object
.search //the search part in location
.match //return string according to regex given
[1] //second result (result in parenthesis)
//--------Use in a function---------
function getQuery(txt){
var result = location.search.match(new RegExp(txt + "=([^&]+)&*.*$"));
return result === null ? undefined : result[1];
}
http://jsfiddle.net/DerekL/J4FfZ/

javascript / jquery modify query string parameter

I need to add or, if it already exists, modify one parameter of a URL query-string.
If I for example want to set param to the value newvalue,
http://example.org/file.php should lead to http://example.org/file.php?param=newvalue
http://example.org/file.php?abc=def should lead to http://example.org/file.php?abc=def&param=newvalue
http://example.org/file.php?param=oldValue should lead to http://example.org/file.php?param=newvalue
I know about the URI.js library, but it's smallest possible size of 21kb (non-gziped) is too big for me.
I am looking for either a small library to modify url-query-strings, or a small piece of code which does this for me.
Here's a solution in all JS, although it would make sense to make this a combo js/php script
var myParam = "foo"
var oldValue = "bar"
var newValue = "fighters"
var queryPairs = window.location.search.substr(1).split("&");
var queryParams = [];
queryPairs.forEach(function(element, index, array){
var pair = element.split("=");
queryParams[pair[0]] = pair[1];
})
if (queryParams[myParam] == oldValue){
queryParams[myParam] = newValue;
queryPairs = [];
for (var index in queryParams){
queryPairs.push(index + "=" + queryParams[index]);
}
var baseUrl = window.location.href.split("?")[0];
var newSearch = queryPairs.join("&")
var newUrl = baseUrl + "?" + newSearch
window.location = newUrl;
}
My (pretty long) version:
if (location.search.match(/([?&]param)=([^&#]*)/g)) {
location.search = location.search.replace(/([?&]param)=([^&#]*)/g, '$1=' + newvalue);
} else if (location.search.match(/([&][^&#]*)=/g)) {
location.search = location.search + "&param=" + newvalue;
} else {
location.search = location.search + "?param=" + newvalue;
}

Categories

Resources