Basically I have a string variable that is composed of two other variables separated by a comma:
item = "Pencil";
amount = 5;
entry = item + "," + amount;
*export entry to csv
So the "entry" variable should be in the correct format to save as a comma separated file. Is there some command that will take this variable and save it as a csv, or any other format easily opened in a spreadsheet for later use? The entry variable will change and the new information will need to be appended to the csv file if it already exists. So let's say if we also had:
item = "Paper";
amount = 25;
entry = item + "," + amount;
*export entry to csv
The resulting csv file should be:
Pencil,5
Paper,25
I've done a bit of searching through other questions, but most folks seem to be trying to do more complex things (e.g., dealing with server vs. client-side issues) while I'm just trying to figure out how to get data I'm working on my own computer in javascript to a saveable file. Seems like that isn't the case for many questions being asked though. I'm sure there's a simple answer out there and hopefully just a single command or two. However, I've been wading through a lot of semi-related posts that aren't too clear, so I figured this would be quicker.
It is perfectly possible, using some FileSaver implementation. I believe it exists natively on IE10, but still needs a shim on other browsers.
I've written a light-weight client-side CSV generator library that might come in handy. Check it out on http://atornblad.se/github/ (scroll down to the headline saying Client-side CSV file generator)
As I said, it requires a functioning FileSaver implementation handling calls to window.saveAs(). Check out Eli Grey's solution on http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
When in place, you simply generate and save CSV files on the fly like this:
var propertyOrder = ["name", "age", "height"];
var csv = new Csv(propertyOrder);
csv.add({ name : "Anders",
age : 38,
height : "178cm" });
csv.add({ name : "John Doe",
age : 50,
height : "184cm" });
csv.saveAs("people.csv");
Related
I ultimately have to consume some data from a Javascript file that looks as follows:
Note: The base64 is illustrative only.
function GetTripsDataCompressed() { return 'QlpoOTFBWSZTWdXoWuEDCAgfgBAHf/.....=='; }
GetTripsDataCompressed() returns a base64 string that is derived as an array of objects converted to JSON using JSON.NET and the resulting string then compressed to bzip2 using SharpCompress with the resulting memory stream Base64 encoded.
This is what I have and cannot change it.
I am struggling to find a bzip2 JavaScript implementation that will take the result of:
var rawBzip2Data = atob(GetTripsDataCompressed());
and convert rawBzip2Data back into the string that is the JSON array. I cannot use something like compressjs as I need to support IE 10 and as it uses typed arrays that means IE10 support is out.
So it appears that my best option is https://github.com/antimatter15/bzip2.js however because I have not created an archive and only bzip2 a string it raises an error of Uncaught No magic number found after doing:
var c = GetTripsDataCompressed();
c = atob(c);
var arr = new Uint8Array(c);
var bitstream = bzip2.array(arr);
bzip2.simple(bitstream);
So can anyone help me here to decompress a BZip2, Base64 encoded string from JavaScript using script that is IE 10 compliant? Ultimately I don't care whether it uses https://github.com/antimatter15/bzip2.js or some other native JavaScript implementation.
It seems to me the answer is in the readme:
decompress(bitstream, size[, len]) does the main decompression of a single block. It'll return -1 if it detects that it's the final block, otherwise it returns a string with the decompressed data. If you want to cap the output to a certain number of bytes, set the len argument.
Also, keep in mind the repository doesn't have a license attached. You'll need to reach out to the author if you want to use the code. That might be tricky given that the repository is eight years old.
On the other hand, the Bzip2 algorithm itself is open-source (BSD-like license), so you can just reimplement it yourself in Javascript. It's just a few hundred lines of relatively straight-forward code.
Please tell me this is possible. I have a .txt file with data arranged like a spreadsheet (i would use excel instead but i dont have it and am broke) and would like to pull from it and assign as a variable.
Ex. (bla.txt)
first line is headers
Second is data
A|B|C
1|2|3
Would like to have them assigned as
Var x= A1
Var y= B2
Var z= C3
Any help would be appreciated.
Ps. All is on a closed circuit so no security issues.
It would be helpful if you could post your .txt file.
Also if you would like to use excel but cant afford it you should try LibreOffice or OpenOffice. They are both free and (at least LibreOffice is) FOSS.
To load this file into your javascript you can use Jquery to load it like this:
$.get('/path/to/data.txt', function(data) { //Gets file 'data.txt' and stores it in variable 'data'
//Code to execute after loading file
/*I’m not sure exactly how your .txt file is formatted so I don't know
How you want it stored into separate variables.
But you can do that here*/
});
Hopefully this at least helps you get started.
This simple code might help for extracting the data from individual lines.
Note: But this will work when you have one character only between |
example
A|B|C 1|2|3
but will not work for
AA|BC|CS 11|2|3
Here it is
var line = "A|B|C 1|2|3";
var x = line.charAt(0) + line.charAt(6);
var y = line.charAt(2) + line.charAt(8);
var z = line.charAt(4) + line.charAt(10);
Use other string functions to get your job done for the second case i pointed out.
Refer to this w3schools page for more help http://www.w3schools.com/js/js_string_methods.asp
My problem is, I would like to create "pretty" URLs for visitors that look like this:
http://domain.com/Name
I have users that often send friends to my service, and I have been created customized pages for each one with the person's First Name in the headline. E.g., "John, here's an easy way to fix this widget"
I then save the page as an index.html file in a custom folder so the link structure for the custom page is domain/Name with Name being their First Name.
This is getting tedious and I would love to use Javascript to automate the process. However, the only documentation I can find on passing variables to Javascript involves "ugly" domains such as domain/jspass2.html?FirstName=John&LastName=Smith
Is there a way to beautify these domains and still pass the variables to a javascript code that inputs their name into the html code? I don't want to "cloak" an ugly domain (using a href, for example)
Thanks for the help!
Well, you could make it "prettier" by making the querystring cleaner.
example:
http://www.domain.com/?John,Smith
The javascript in your index file can read that.
var getQueryString = function() {
queryString = window.location.search;
queryStringCleaned = queryString.substring(queryString.indexOf('?') + 1 );
return queryStringCleaned;
};
if "http://domain.com/Name" is your domain, variable firstName will have the value "Name".
var firstName = window.location.pathname.match(/([\w-]+)\/?.*/)[1];
You could just take the whole URL in JS, and parse it "by hand". Use this regex (for example) to find the parameters passed.
In addition to Paul, I wrote you something that extracts the first name field from the url you provided. If the format is consistent, and you can obtain the url in javascript, you can use this. You may possibly have to create the page first, then redirect the user because javascript is a client side language and the page will already be rendered.
var url = "domain/jspass2.html?FirstName=John&LastName=Smith";
url = url.slice(url.indexOf("FirstName=") + 10, url.length);
url = url.slice(0, url.indexOf("&"));
This question is close but not quite close enough.
My HTML5 application reads a CSV file (although it applies to text as well) and displays some of the data on screen.
The problem I have is that the CSV files can be huge (with a 1GB file size limit). The good news is, I only need to display some of the data from the CSV file at any point.
The idea is something like (psudeo code)
var content;
var reader = OpenReader(myCsvFile)
var line = 0;
while (reader.hasLinesRemaning)
if (line % 10 == 1)
content = currentLine;
Loop to next line
There are enough articles about how to read the CSV file, I'm using
function openCSVFile(csvFileName){
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var s = "";
};
r.readAsText(csvFileName);
}
but, I can't see how to read line at a time in Javascript OR even if it's possible.
My CSV data looks like
Some detail: date, ,
More detail: time, ,
val1, val2
val11, val12
#val11, val12
val21, val22
I need to strip out the first 2 lines, and also consider what to do with the line starting with a # (hence why I need to read through line at a time)
So, other than loading the lot into memory, do I have any options to read line at a time?
There is no readLine() method to do this as of now. However, some ideas to explore:
Reading from a blob does fire progress events. While it is not required by the specification, the engine might prematurely populate the .result property similar to an XMLHttpRequest.
The Streams API drafts a streaming .read(size) method for file readers. I don't think it is already implemented anywhere, though.
Blobs do have a slice method which returns a new Blob containing a part of the original data. The spec and the synchronous nature of the operation suggest that this is done via references, not copying, and should be quite performant. This would allow you to read the huge file chunk-by-chunk.
Admittedly, none of these methods do automatically stop at line endings. You will need to buffer the chunks manually, break them into lines and shift them out once they are complete. Also, these operations are working on bytes, not on characters, so there might be encoding problems with multi-byte characters that need to be handled.
See also: Reading line-by-line file in JavaScript on client side
i am facing the problem that i have to translate a larger html and javascript project into several languages. The html content was no problem, but the numerous javascript files are problematic, since i was a bit lazy during the development process. For instance, if i needed a message text, i just added it in the concerning position.
My approach now is, that i am using a build-in file search (Eclipse) for every occurrence of " and ', which i am getting line-wise. This would be extremely time consuming and errors are unavoidable.
Here are some examples that occur in the files:
var d = "Datum: " + d.getDate()+"."+(d.getMonth()+1)+"."+d.getFullYear();
showYesNoDialog("heading text","Are you sure?",function(){};
Sometimes i am mixing " and ', sometimes a string goes over several lines:
var list="";
list+='<li data-role="list-divider">';
list+='Text To Translate';
list+='</li>';
Things i don't want to get, are jquery selectors, e.g.:
$("input[name^=checkbox]").each(function () {};
Do you see any time saving method to get all of the strings that i would like to translate?
Regex? A java interpreter? Grep?
I know, that is a bit unusual question.
So any suggestion would be great.
Thanks in advance!
It is better to use some kind of the lexical scanner that converts the code into the tokens and then walk over the list of tokens (or syntax tree). There is a number of such tools (I even created one of them myself - here you can find some of the examples https://github.com/AlexAtNet/spelljs/blob/master/test/scan.js).
With it you can scan the JS file and just iterate over the tokens:
var scan = require('./..../scan.js');
scan(text).forEach(function (item) {
if (item.str) {
console.log(item);
}
});