just felt like asking this as there are always jewels popping up on stackoverflow :)
What I have is the following list:
list1 = [['command','arg1','arg2'], ['command2','arg1'], ... ]
How would you recommend to transform it into a string in order to be passed as ONE GET argument?
e.g.
http://webgame_site.com/command_list/?data=...
What I am currently doing is separating lists using commas , ; , but I don't like this idea as the method would break if I decide to introduce these within strings.
I'm trying to be as compact as possible.
One idea I've had is to encode the list into base64:
[['command','arg1','arg2'], ['command2','arg1']]
=> "W1snY29tbWFuZCcsJ2FyZzEnLCdhcmcyJ10sWydjb21tYW5kMicsJ2FyZzEnXV0="
which is shorter than URIencode
Any ideas? :)
Convert it to json then encode the characters using encodeURI.
var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = encodeURI(JSON.stringify(list1));
alert(encoded);
Edit for base64:
var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = btoa(JSON.stringify(list1));
alert(encoded);
alert(atob(encoded));
jQuery.param() sounds good.
Related
I have a string:
Name1<br/>Name2<br/>Name3
Im looking to get a choice selector or an array with just the Names as values. I know you can get just the text of a string, but I cant figure out a way separate them. This list changes so I cant hard code the names in.
I cannot find any code nor do I have anything yet.
Use the split function:
var text = "Name1<br/>Name2<br/>Name3";
var list = text.split("<br/>");
This is easily accomplished using JavaScript built-in split().
var input_s = "Name1<br />Name2<br />Name3";
var input_r = input_s.split("<br />");
I have a full string consisting of something like this [(data1.1)(data1.2)][(data2.1)(data2.1)]
Ive read you can do something smart with match function and regex. I want two arrays with the data loaded out of the parentheses.. How in earth do i do that? Please use my string as example.
I came up with this abomination:
var array = s.replace(/^\[|\]$/g,'').split('][').map(function(a){
return a.replace(/^\(|\)$/g,'').split(')(')
});
http://jsfiddle.net/8kLhc/
Also if you deliberately save or transmit data like this then you should really have a look at JSON or proper database design.
I wasn't entirely sure what you were after, but I'm assuming this
var what = '[(data1.1)(data1.2)][(data2.1)(data2.2)]',
have = [],
you = [],
tried = /\[\(([^)]*)\)\(([^)]*)\)\]/g;
what.replace(tried, function (use, brain, forthis) {
you.push((have.push(brain), forthis));
});
console.log(have, you);
// ["data1.1", "data2.1"] ["data1.2", "data2.2"]
I'm trying to parse a JSON string and I can't get it to work because of illegal chracters - which I cannot find...
Here is what I have:
make = function (el) {
var config = el.getAttribute("data-config");
console.log(config);
var dyn = $.parseJSON(config)
console.log(dyn);
}
var a= document.createElement("Star Icon");
console.log(a);
make(a);
I'm not really sure how to correctly unescape the JSON in my original string "a", so that it works.
Question_:
Which quotation marks do I need to escape to get this to work?
Thanks!
EDIT:
Ok. I figured it out using Jquery (I'd prefer Javascript-only though). This works:
make = function (el) {
var config = el.attr("data-config");
console.log(config);
var dyn = $.parseJSON(config)
console.log(dyn);
}
var c = $('<a href="#" class="template" data-config=\'{"role":"button","iconpos":"left","icon":"star","corners":"false","shadow":"false", "iconshadow":"false", "theme":"a","class":"test", "href":"index.html","text":"Star Icon", "mini":"true", "inline":"true"}\'>Star Icon</a>')
console.log(c);
make(c);
So escaping the start/end quotations of the JSON string seems to do the trick. The actual problem was that I can not use document.createElement with a full string. I can only create the element document.createElement(a) and then set innerHTML. Need to look into this some more.
If someone can tell me a Javascript-only way how to do this, please let me know.
Thanks!
Strings and object keys in JSON must be double quoted. Double quotes in attributes are not valid, so you'll need to escape them with ".
Also, you probably want to use booleans true/false instead of strings "true"/"false".
var a = document.createElement('Star Icon');
Notice this is completely unreadable and #millimoose's suggestion about just setting the attribute afterwards will make this much easier to deal with in the long run.
I have something I am trying to accomplish.
I'd like to take an array built with AJAX/xml.
array[/word0/, /word1/, /word2/]
and put this into a form that could be used in a .match():
result = string.match(array)
I have tried using a for loop and stepping through the array using string.match(array[i]) to no avail.
Is there an easy way to do this?
Edit: You may have a syntax problem. The following is not valid syntax:
array[/word0/, /word1/, /word2/]
Something like this fixes it:
var regexps = [/word0/, /word1/, /word2/];
Original answer:
Javascript RegExps already do this. You're looking for:
var regexp = /word0|word1|word2/;
Assuming your list of matches comes back in the right format, you could achieve this like so:
var words = ["word0", "word1", "word2"];
var regexp = new Regexp(words.join("|"));
str.match(regexp);
http://jsfiddle.net/KALPh/
Your approach was fine. Here's my implementation:
var regexes = [/^def/, /^abc/],
testString = 'abcdef',
numRegexes = regexes.length;
for(var x=0;x<numRegexes;x++) {
alert(regexes[x].test(testString));
}
To initialize your array, use
var array = [/word0/, /word1/, /word2/];
Then you can use
str.match(array[i])
If your problem is the transmission in "AJAX/xml", then you'll need to build the regular expressions client side with new RegExp(somestring) where somestring might for example be "word0" : you can't embed a regex literal in XML.
I have one string
var str = '';
str += 'category='+jv('category')+'&';
str += 'refresh_rate='+jv('refreshRate')+'&';
str += 'submit=Y';
now I want to take values from jv('category') and jv('refreshRate') in separate string in javascript (I want to extract values after "=" and before "&").
Thanks.
I've used this: http://blog.stevenlevithan.com/archives/parseuri
URI Parser in the past and find it simple to use and it doesn't rely on any other libraries. Its also pretty lightweight.
The author has a demo page but doesn't really explain how to use it..
Its really simple, you just do something like this:
var url = "http://my-site.com:8081/index.html?query=go&page=2";
var parsed = parseUri(url);
From there you can get things like the host/protocol/port/etc..
When dealing with the querystring you do
var page = parsed.queryKey.page;
alert(page); //alerts 2
Click the parse button on the demo page to see all properties of the parsed URI object that you can access..
You can use http://github.com/allmarkedup/jQuery-URL-Parser or any other URL parser for this sort of string.