Removing "," at the beginning of a line CSV - javascript

i want to convert a .csv file and write a new one. However I am not able to remove the first , i am kinda stuck here and it is driving me crazy.
This is my code:
var extractedtasks = tasks.slice(0, 3)
var extractedtasksformated = extractedtasks.toString().replace(/,$/g, "\n")
let csvformat = "EMAIL,PASSWORD,MAILBOX"
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksformated.replace(/,^/g,
""))
console.log(chalk.green("Successfully updated the CSV file"))
That's the output i am getting in the newly generated file
EMAIL,PASSWORD,MAILBOX
example1#gmail.com,Password123,example#gmail.com:password
,example2#gmail.com,Password123,example#gmail.com:password
,example3#gmail.com,Password123,example#gmail.com:password
Output extractedtasks:
[
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
Output extractedtasksformated:
,example3#gmail.com,Password123,example#gmail.com:passwordxample#gmail.com:password

Because extractedtasks is an array, instead of converting it to a string you should just join it with the expected separator:
extractedtasks = [
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
extractedtasksJoined = extractedtasks.join("\n")
// "example1#gmail.com,Password123,example#gmail.com:password\r\nexample2#gmail.com..."
// depending on the target line separator, you should also probably
// remove the "\r"
extractedtasksJoined = extractedtasksJoined.replace("\r", "")
// finally
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksJoined + "\n")

Related

What am I receiving undefined when building this string? Javascript

I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!
Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"
You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));

Make comma separated list from different paths

I have list of paths as follows in multiple lines.
abc/xyz/../a1.txt
abc/xyz/../a2.txt
abc/xyz/../a3.txt
abc1/xyz/../a4.txt
abc1/xyz/../a5.txt
abc1/xyz/../a6.txt
i want to remove all paths and extract only file names as follows
"a1.txt","a2.txt","a3.txt" and
"a4.txt","a5.txt","a6.txt"
pls help me.
Let's say the list of paths is stored in one string:
var paths= "abc/xyz/../a1.txt"
+ "\n" + "abc/xyz/../a2.txt"
+ "\n" + "abc/xyz/../a3.txt"
+ "\n" + "abc1/xyz/../a4.txt"
+ "\n" + "abc1/xyz/../a5.txt"
+ "\n" + "abc1/xyz/../a6.txt";
You just need to split it by lines and reduce each entry to file name (e.g. by using regex):
var fileNamePattern = /[^\/]+$/;
var fileNames = paths.split("\n").map(function (entry) {
return fileNamePattern.exec(entry)[0];
}
For more information about how to use regex look at this link and here you can find how to use the map method.
Update
Here you can find an example
You could use regular expressions to convert a multi-line string with paths into an object that will have an array of file names per folder, where the folder name is used as the object's property name:
// Test data, with some border cases:
var paths = " abc/xyz/../a1.txt\n" +
"abc/xyz/../a2.txt\r\n" +
" \n" +
" no-folder.txt \n" +
"abc/xyz/../a3.txt \n" +
" abc1/xyz/../a4.txt\n" +
"abc1/xyz/../a5.txt\n" +
"abc1/xyz/../a6.txt\n" +
" ";
var filesPerFolder = paths.split(/\r\n|\n/).reduce(function (filesPerFolder, path) {
path = path.trim();
if (path.length) {
var folder = path.replace(/[^\/]*$/, '');
(filesPerFolder[folder] = filesPerFolder[folder] || []).
push(path.substr(folder.length));
}
return filesPerFolder;
}, {});
filesPerFolder will be
{
"abc/xyz/../": [
"a1.txt",
"a2.txt",
"a3.txt"
],
"": [
"no-folder.txt"
],
"abc1/xyz/../": [
"a4.txt",
"a5.txt",
"a6.txt"
]
}
The above code:
recognises LF or CRLF line breaks
skips white-space around paths
skips empty lines
can handle lines that have file names without folder prefix
Here is a fiddle where you can type the list as input, press the Go button and see the Json encoded filesPerFolder.
There are plenty of ways to work with that object. For instance, you could print out the contents as follows:
Object.keys(filesPerFolder).forEach(function(folder) {
console.log('Contents of folder "' + folder + '": '
+ JSON.stringify(filesPerFolder[folder]));
});
This will output (with the example data above):
Contents of folder "abc/xyz/../": ["a1.txt","a2.txt","a3.txt"]
Contents of folder "": ["no-folder.txt"]
Contents of folder "abc1/xyz/../": ["a4.txt","a5.txt","a6.txt"]
Or, if you want to print each of the files with prefixed folder (which would be a clean version of the input):
Object.keys(filesPerFolder).forEach(function(folder) {
filesPerFolder[folder].forEach(function(file) {
console.log(folder + file);
});
});
Output:
abc/xyz/../a1.txt
abc/xyz/../a2.txt
abc/xyz/../a3.txt
no-folder.txt
abc1/xyz/../a4.txt
abc1/xyz/../a5.txt
abc1/xyz/../a6.txt
Assuming this is string, first store different paths inside an array using split for newline in the string:
arr = str.split(/\n/);
Then loop over array and use pop to store file name in another array(say file_names):
file_names.push(arr[i].split('/').pop())

Convert a string with function calls to an array

I need to convert this function call to a simple array[] but it's not working for some reason.
Here's the fiddle
var LongCombinedReady = $('#GeoImageLat').val(exifObject.GPSLatitude + "," + "'" + exifObject.GPSLatitudeRef + "'")
var LatCombinedReady = exifObject.GPSLongitude + "," + "'" + exifObject.GPSLongitudeRef + "'"
//an attemp to take the values and convert them to an array but it doesn't work.
var LongCombined = [LongCombinedReady];
var LatCombined = [LatCombinedReady];
I've commented it all out in the fiddle also here's an image with GeoCoords if you don't have one for testing.
Test Geotag image
Basically I read the images Geotag and then convert the tag from DMS to DD so it can be used for something like Google maps.
There are three problems:
you are missing an apply in line 49
you are applying array with one item being a string while function you are applying to expects four parameters
at line 43 LongCombinedReady is an jQuery object

Writing onto HTML page

So for a brief context, my program reads in a file and displays it onto the html page. The code below uses a regex expression to read that file and extract the errors. Instead of using console.log each time and debugging, is there any I way I could just write the results onto the HTML page?
When I used:
document.getElementById("").innerHTML
it would just print out the last summary instead of printing out all of the summaries.
I tried using a controller and ng-repeat (AngularJS) to do it, but somehow I did not do it right.
Any ideas -- doesn't have to be in AngularJS???
while ((match = reDiaBtoa.exec(reader.result)) != null) {
if (match.index === reDiaBtoa.lastIndex) {
reDiaBtoa.lastIndex++;
}
// View your result using the match-variable.
// eg match[0] etc.
// extracts the status code: ERROR
if (match[2] === "ERROR" || match[2] === "FATAL" || match[2] === "SEVERE") {
console.log("Time: " + match[1]);
console.log("Thread Name: " + match[3]);
console.log("Source name & line number: " + match[4]);
console.log("Log Message: " + match[5] + '\n');
console.log("-----------------------------------------------------------------");
}
} //end of the while loop ((match = reDiaBtoa.exec.....))
If you use
document.getElementById("someId").innerHTML =
it'll overwrite the existing html.
instead, use
document.getElementById("someId").innerHTML +=
Create a string variable before your while loop and then append to it in your loop:
var outputToDisplay = "";
//While loop
outputToDisplay += "Time: " + match[1];
//etc
//End While
document.getElementById(theId).innherHTML = outputToDisplay;

How to escape double quotes between JS and JSON

I'm trying to construct a String in JS that can be passed into JSON as an with a very particular format. Desired result is a string of the following form:
["PNG","350x150","127 KB"]
Where PNG correspond to a particular image's type, where 350x150 is the image's dimensions and where 127 KB is the image's size. Each of these threee values are string variables:
var imgType = getImageType(); // Returns "PNG"
var imgDim = getImageDim(); // Returns "350x150"
var imgSize = getImageSize(); // Returns "127 KB"
var imgDescription = '["' + imgType + '","' + imgDim + '","' + imgSize + '"]';
// Sanity check
alert(imgDescription);
iVO.images[thisImage] = {
"fizz":"buzz",
"imgDesc":imgDescription,
"foo":"bar"
}
alert(JSON.stringify(iVO));
The first alert (on the imgDescription variable) prints:
["PNG","350x150","127 KB"]
So far, so good. However, the minute we pass it to the iVO construct and stringify the resultant JSON, it generates the following output (after I pretty print format it):
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":"[\"PNG\",\"350x150\",\"127 KB\"]",
"foo":"bar"
}
}
}
All of my double quotes (") have been escaped (\")!!! Also, the value for imgDesc is enclosed in double-quotes, which is not what we want (see desired JSON below):
When I send this JSON back to the server its causing the server to choke.
Not sure what is going on here but I've tried several other suggestions, including replacing my double-quotes with '\x22' instances which didn't help.
Any ideas as to what would fix this to get the desired result from JSON.stringify(iVO)? Ultimately that's the only thing that matters, that the we end up sending the following to the server:
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":["PNG","350x150","127 KB"],
"foo":"bar"
}
}
}
No escaped double-quotes, and the value for imgDesc is not double-quoted. Thanks in advance!
Why don't you just put imgDescription as regular array
var imgDescription = [imgType , imgDim, imgSize];
Stringify should take care of what you are trying to do, otherwise you are passing imgDescription as a string and stringify would escape the quotes.
e.g.
var imgType = "PNG";
var imgDim = "350x150";
var imgSize = "127 KB";
var d = {
"fizz":"buzz",
"imgDesc":[imgType , imgDim, imgSize],
"foo":"bar"
}
console.log(JSON.stringify(d));
Output:
{"fizz":"buzz","imgDesc":["PNG","350x150","127 KB"],"foo":"bar"}

Categories

Resources