I have converted my .xml code to .json
For xml I am using something like this:
var stage = xml.getElementsByTagName("stage" + game.current_stage)[0];
How can you do that in json?
I want something like this:
var stage = json."stage"+ game.current_stage;
You can still use the zero index for the JSON, and the correct syntax is:
var stage = json["stage" + game.current_stage][0];
If I understand the question:
var stage = json["stage"+ game.current_stage];
var stage = json["stage" + game.current_stage];
would you like to read by using Javascript or what?
Then below code helps. Please try with that
var stage = JSON.parse(json)["stage"+ game.current_stage];
Related
I scrape sites for a database with a chrome extension,
need assitance with a JavaScript Clean up function
e.g
https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p
my target output is:
_60789694386.html
everything past .html needs to be removed, but since it is diffrent in each URL - i'm lost
the output is in a .csv file, in which i run a JavaScript to clean up the data.
this.values[8] = this.values[8].replace("https://www.alibaba.com/product-detail/","");
this.values[8] is how i target the column in the script. (Column 8 holds the URL)
Well, you can use split.
var final = this.values[8].split('.html')[0]
split gives you an array of items split by a string, in your case'.html', then you take the first one.
Consider using substr
this.values[8] = this.values[8].substr(0,this.values[8].indexOf('?'))
You can use split method to divide text from ? as in example.
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.split('?')[0].replace("https://www.alibaba.com/product-detail/","");
console.log(result);
Not sure i understood your problem, but try this
var s = 'https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p'
s = s.substring(0, s.indexOf('?'));
console.log( s );
For when you don't care about readability...
this.values[8] = new URL(this.values[8]).pathname.split("/").pop().replace(".html","");
Alternate, without using split
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.replace('https://www.alibaba.com/product-detail/', '').replace(/\?.*$/, '');
console.log(result);
You can use the regex to get it done. As of my knowledge you do something like:
var v = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
result = (v.match(/[^\/]+$/)[0]);
result = result.substring(0,result.indexOf('?'));
console.log(result); // will return _60789694386.html
I have a JSON string below that is being stored as a var in JavaScript. I am trying to parse the pieces of the string into variables.
In particular, I need the address, postcode, region, and locality.
This JSON array is being stored as a JS var called "data"
Does anyone know how I can begin parsing out those things? Thank you all!
[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and
Dining","Restaurants"]],"country":"us","email":"kimd#thedussingroup.com","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]
Appreciate the help!
You JSON is an array (since it's contained in [ and ]), so you need:
var data = JSON.parse('[{"addre....}]');
var address = data[0].address,
postcode = data[0].postcode;
and so on...
for(var i in data[0]){
window[i] = data[0][i];
}
alert(address);
You can do this using JSON.parse
var data= your json;
JSON.parse(data);
Update:
In your case you don'e even need to parse you can use directly like
console.log(data[0].address); //returns 2801 Elliott Ave
console.log(data[0].category_ids); //returns [347]
Check this JSFiddle
I want to create a JS array that contains jQuery objects like this:
var oFormFields = new Object;
oFormFields.label = $(document.createElement('label'));
oFormFields.input = $(document.createElement('input'));
Since this crashes my code, i expect this is not possible. Any alternatives? This is my simplified version, I want to include some other properties so I'm able to re-use this in my code when building dynamic forms.
EDIT: Seemed this did work after all... what I wanted to do, was something like this:
var oFormFields = new Object;
oFormFields.name_field.label = $(document.createElement('label')).addClass('nam_field');
oFormFields.name_field.input = $(document.createElement('input')).addClass('nam_field');
This does break my code. I'm pretty new to jQuery, coming from a PHP background I'm having some troubles adjusting to the correct way to work with arrays / objects.
Just use it like this:
var oFormFields = {
label: $('<label />'),
input: $('<input />')
};
You can create the element directly using jQuery. Furthermore, as mentioned in the comments, you should prefer the object literal notation over the new syntax.
var arr = [];
var oFormFields = {};
oFormFields.label = $('<label/>');
oFormFields.input = $('<input/>');
arr.push(oFormFields);
.........
Trying to remove the full url that is being returned to imgurl:
Usually returns something like http://localhost/wordpress/wp-content/uploads/filename.jpg
or http://localhost/wordpress/wp-content/uploads/images/filename.jpg
I'd like to strip off everything except filename.jpg and return it to
ahng_photos_upload_image. Strip off everything to the last forward-slash.
How can I do that with Jquery?
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#ahng_photos_upload_image').val(imgurl);
tb_remove();
}
You don't need jQuery for that, just plain old JavaScript will do :)
alert('http://localhost/wordpress/wp-content/uploads/filename.jpg'.split('/').pop());
In your case:
var filename = imgurl.split('/').pop();
you can use a regular expression in order to achieve this..
var file = imgUrl.replace(/^.*[\\\/]/, '');
Now the file would consist of only the file name ..
If you're pretty confident that the URLs don't have funny stuff like hashes or parameters, a regex like this would do it:
var filename = imgurl.replace(/^.*\/([^/]*)$/, "$1");
Also: don't forget to declare "imgurl" with var, and you should probably use .prop() instead of .attr() if your version of jQuery is 1.6 or newer:
var imgurl = jQuery('img', html).prop('src');
Also jQuery internally turns the two-argument form of the function into this:
var imgurl = jQuery(html).find('img').prop('src');
so you might as well code it that way.
One further option:
var filename = imgurl.substring(imgurl.lastIndexOf('/') + 1);
JS Fiddle demo.
Here you have
var filename = imgurl.split('/').slice(-1);
Good luck!
Try this one:
imgurl.split('/').slice(-1);
Edit: Look at the version of #Andy who uses the pop() method, the latter being faster than slice(-1).
Note that if you don't know if you have forward or backward slashes, you are better off using the RE version of split:
"path".split(/[\/\\]/).slice(-1)
Here is an answer that will work when your file name is like ./file.jpg
var extension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
var baseName = fileName.replace(/^.*\/([^/]*)$/, "$1");
var path = fileName.replace(/(^.*\/)([^/]*)$/, "$1");
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.