javascript removing characters from multiple strings using a for loop - javascript

I'm reading a log file using file reader and then want to do some text manipulation using javascript, to use the read data further in my program. So far I managed to split my input by lines, but now that I want to format the specific strings in the array nothing happens. Is this due to not declaring the array globally? Basically I wanted to do a for loop that checks all the strings inside my array and remove " " (four blank spaces) that appear at the start for some of my strings. This is my code
$("#draftlog").change(function() {
var logFile = $('#draftlog').get(0).files[0];
//gets first file from draftlog
var reader = new FileReader;
reader.readAsText(logFile);
reader.onload = function(e) {
var rawLog = reader.result;
//reads first file from draftlog as text
var re=/\r\n|\n\r|\n|\r/g;
arrayOfLines = rawLog.replace(re,"\n").split("\n");
//splits the text into an array of strings for every new line
for(x=0;x<arrayOfLines.length;x++) {
arrayOfLines[x].replace(/ /g,'');
}
console.log(arrayOfLines);
};
});
my input will typicaly look like this:
Event #: 7952945
Time: 5.2.2015 17:14:54
Players:
TheDoktorJot
Arlekin
Jokulgoblin
Felo
Petrolit
Greyjoy
--> Susti
themuse1975
n0sfea
------ FRF ------
Pack 1 pick 1:
Abzan Runemark
Rakshasa's Disdain
Reach of Shadows
Grim Contest
Aven Skirmisher
Lotus Path Djinn
Formless Nurturing
Tasigur's Cruelty
Temur Battle Rage
Return to the Earth
--> Temur Sabertooth
Fascination
Jeskai Barricade
Arcbond
Rugged Highlands
Pack 1 pick 2:
Sandblast
Sultai Runemark
Jeskai Sage
Hooded Assassin
Pressure Point
Gore Swine
Whisperer of the Wilds
Mardu Runemark
Ambush Krotiq
Write into Being
Qarsi High Priest
Hewed Stone Retainers
Wardscale Dragon
--> Mastery of the Unseen

Strings are immutable, you have to write it back
for(x=0;x<arrayOfLines.length;x++) {
arrayOfLines[x] = arrayOfLines[x].replace(/ /g,'');
}
You could also just trim it to remove leading and following whitespace
arrayOfLines[x] = arrayOfLines[x].trim();

Related

Replace javascript and check order

I'm trying to replace line breaks with "," to every line end up like this 85aacb80-bh00-40e3-813c-5ad62ee93f42,324234,user#gmail.com
And make sure of the format, the long numbers and letters to be always the 1st, the id "324234" to be the second and email field to be always at 3rd. If some line is not matching the order go get deleted and be writed into another output file.
Though I'm stuck here It doesn't work..
The content of the txt file is this
85aacb80-bh00-40e3-813c-5ad62ee93f42
324234
usernine#gmail.com
And this is the code I'm trying
var neek = require('neek');
var readable = 'messagematch.txt';
var writable = 'outputmessagematch.txt';
neek.unique(readable, writable, function(result){ \\Here I remove duplicate lines
console.log(result);
});
const replace = require('replace-in-file');
const options = {
files: 'outputmessagematch.txt',
from: '\n',
to: ',',
};

How to avoid long for-loops for creating multiple arrays (javascript)

I´m stuck with a problem... given an input number I´m trying to output a string of length 4. The string has to be divided into 2 parameter sections "On"/"Off".
For example:
-If the input number is 16, then the string should get combined as follows:
"On" section = "On" * Math.floor(16/5) = 3 --> "On On On".
"Off" section should be: length-On-section = 4-3 = 1 --> "Off".
Hence the string should look like "On On On Off".
I´m currently trying to narrow my solution to a nicer approach than using a for loop. I have to repeat this process various times in my function to create strings following the same approach but in various lengths and "On"/"Off" section ratios. but I´m not sure how to set it up properly..
this is one example:
function hoursTop(hour) {
var lights = [], on = Math.floor(hour/5), off = 4 - topLightsOn;
for(var i=1; i<=on; i++){
lights.push('On');
}
for(var j=1; j<=Off; j++){
lights.push('Off');
}
return lights.join("");
}
This produces way too much code overall.. Thanks for helping me out!
You can use String#repeat to create the strings, then concat them, and trim the extra spaces:
function hoursTop(hour) {
var on = Math.floor(hour/5), off = 4 - on;
return 'on '.repeat(on) + 'off '.repeat(off).trim();
}
console.log(hoursTop(16));
Or you can use Array#fill to create the array, then concat them, and join the array to a string:
function hoursTop(hour) {
var on = Math.floor(hour/5), off = 4 - on;
return Array(on).fill('on').concat(Array(off).fill('off')).join(' ');
}
console.log(hoursTop(16));

Search for tab character in a specific line of a tab delimited text file

I'm loading a tab delimited text file using the FileReader API. Once loaded I need to find the tab location in the first line, parse out the characters preceding the tab, do some stuff with the parsed characters, then proceed to the second line, parse out the characters before the first tab in the second line, do some stuff with the parsed characters, then proceed to the third line, and so on until the end of the file.
I'm not a coder. I could use some help on the script to perform these operations.
Update/Edit (as requested): Specifically, taking it step by step:
I'm able to load the tab delimited file.
I'm able to step through the lines of the file (row 15+).
I'm making progress on stepping through the lines in the file (row 15+).
But I'm failing in the ability to perform a set of tasks as each line is read.
As each line is read, I want to parse out the characters in the line that are prior to the first tab character. In the example file contents below, I want to parse out 5, then I wish to take action on the 5. After that I want to parse out 10, then take action on the 10. Then I want to parse out 200 and take action on the 200. Then the script will end.
I'm assuming as each line is read that I want to call another function and send the contents of the first line to the new function. The new function will then parse out the characters before the first tab. Is this correct? If not, then what should I be doing? After that I'm assuming I should call another function, which will take the action on the parsed characters. Is this correct (and if not, what should I be doing instead)?
If I'm correct that I should be calling another function with each line read, then how do I do so (including sending the contents of the line)? In the code shown, I've been unsuccessful in figuring out how to do this.
Thank you,
Andrew
Example of tab delimited file:
5 15:00:05 2 1
10 15:00:10 2 2
200 15:03:20 2 3
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function (e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
// Entire file
fileDisplayArea.innerText = reader.result;
// Count of lines in file
var lines2 = reader.result.split("\n").length;
fileDisplayArea2.innerText = "The number of lines in the text file is: " + Number(lines2-1);
// Attempt at an action per line
var lines = reader.result.split('\n');
for (var line = 0; line < lines.length; line++) {
//console.log(lines[line])
//with each line, how can I call another function and send along with the call the contents of the line?
fileDisplayArea3.innerText = lines;
}
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
Select a text file:
<input type="file" id="fileInput">
<hr />
<pre id="fileDisplayArea"></pre>
<hr />
<pre id="fileDisplayArea2"></pre>
<hr />
<pre id="fileDisplayArea3"></pre>
Here is an example of what you want to do. When looping each line you can get the text of that line with lines[line] from the lines array. You can then pass that text (and in my example the line number) to a function.
In my example the function is doStuff and it then splits the line text by tab character getting an array of "cells" (the values on the line that are delimited by tabs). I had the function output the values so that you could see them. You can have it do whatever you need.
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function (e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
// Entire file
fileDisplayArea.innerText = reader.result;
// Count of lines in file
var lines2 = reader.result.split("\n").length;
fileDisplayArea2.innerText = "The number of lines in the text file is: " + Number(lines2);
// Attempt at an action per line
var lines = reader.result.split('\n');
for (var line = 0; line < lines.length; line++) {
doStuff(line, lines[line]);
fileDisplayArea3.innerText = lines;
}
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
function doStuff(lineNumber, lineText) {
// do something with the
var cells = lineText.split('\t'); // '\t' is a tab character
cellValues.innerText += "Line: " + (lineNumber + 1) + "\n";
cells.forEach(function(value) {
// do something with each "value" that was delimited by the "tab" characters
// in this example add the value to cellValues
// you can do whatever you want with the "value" here
cellValues.innerText += '\t' + value + '\n';
});
}
Select a text file:
<input type="file" id="fileInput">
<hr />
<pre id="fileDisplayArea"></pre>
<hr />
<pre id="fileDisplayArea2"></pre>
<hr />
<pre id="fileDisplayArea3"></pre>
<hr />
<pre id="cellValues"></pre>
Update: Explanation of doStuff
The first line of the function is var cells = lineText.split('\t'); This does not "replace" the tab characters with commas. What it does is create an array and store it into the cells variable.
In your original code the reason this line fileDisplayArea3.innerText = lines; is displayed with commas is because the lines array is transformed to a string in order to put it into innerText. Internally javascript calls the toString() method on the array which outputs it's elements separated by commas.
So continuing on. cells is now an array of the values of the line that were separated (delimited) by tab characters. We could use a for loop like you did to iterate the lines but I chose to use forEach. forEach will loop through (as the name suggests) each element of the array passing it's value to the function. The value is now available to do whatever we want with it i.e. make decisions, do math on it, etc... or (in my case) write it out to be seen.

Want to remove various strings from filename before save

I have a JSX script I've written for Photoshop and at the end of this script, before saving, I want to check the filename for various strings and remove them if they exist. What I've written so far only removes the first element in the array it encounters - in the case below it hits the regex and then moves on to save.
An example of a filename encountered is: "PRNT-AB-Navy Blush Oil pallet painting-18x24--REV 27x21.jpg"
What I want the resulting name to be is: "AB-Navy Blush Oil pallet painting"
So I need a little help understanding how can I remove all elements of the array that exist in any given filename?
var array = ["PRNT-", "--REV ", "-REV ", ".jpg", ".tif", ".psd", new RegExp(/\d+[x]\d+/g)];
var docName = activeDoc.name
for (var i = array.length; i >= 0; i--) {
var newName = docName.replace(array[i], '');
}
Thanks!
Welcome to Stack Overflow.
I haven't worked out your file name convention but this will replace the string with what you want without having to loop over each element.
var s = "PRNT-AB-Navy Blush Oil pallet painting-18x24--REV 27x21.jpg";
alert(replace_filename(s));
function replace_filename(str)
{
var rexp = new RegExp(/PRNT-|-\d*x\d*|--REV\s+\d*x\d*|.jpg|.tif.psd/gim);
return str.replace(rexp, "");
}
// AB-Navy Blush Oil pallet painting

Converting CSV to JSON in a strange format

I have a lot of geo's which I want to use in webgl globe.
The format for Webgl is
Sample for Googles .json file in their working webgl globe source [["1993",[long, lat,weight,long, lat,weight],["1994",[long, lat,weight,long, lat,weight,long, lat,weight,long, lat,weight]]]
I've been looking for a way to convert this but i can't find a converter online.
Does anyone know where I can find a converter for this format or suggest a way to do this.
Sample of my data:
- Year Latitude Longitude Magnitude
- 1995 -82.8627519 -135 0.11
- 1995 -54.423199 3.413194 0.01
- 1994 -53.08181 73.504158 0.01
- 1994 -51.796253 -59.523613 0.04
- 1993 -49.280366 69.348557 0.02
- 1993 -41.4370868 147.1393767 0.18
Looking at this more, I think the json file Google are using is a nested json array of arrays. This
There are multiple ways to parse the data.
The first step is to save the data to a file.
For example:
Year Latitude Longitude Magnitude
1995 -82.8627519 -135 0.11
1995 -54.423199 3.413194 0.01
1994 -53.08181 73.504158 0.01
1994 -51.796253 -59.523613 0.04
1993 -49.280366 69.348557 0.02
1993 -41.4370868 147.1393767 0.18
in raw.txt
The second step is to load and parse data.
With parsing there are a couple of things to keep in mind:
The raw data has an inconsistent number of white spaces separating values, so those need to be collapsed first so we can split a row/line by the space character. Luckily the data doesn't contains names containing spaces so we can use a RegEx like so /\s{2,}/g
We want to gather all the data pertaining to one year into a single list. One way is to use an array and continuously check if it has the year value already. Another is to simply use an Object/associative array/dictionary and not worry about any checks.
Once the data is correctly gathered in a object we pop it into a an array so it matches the format of the data being used.
Here's what I mean:
xhr = new XMLHttpRequest();
xhr.open('GET', '/globe/raw.txt', true);
xhr.onreadystatechange = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var lines = xhr.responseText.split("\n");//split .txt file into lines
var data = [];//prepare an array to hold the end result
var dict = {};//use an Object/Dictionary to collapse data from same key/year
for(var i = 1 ; i < lines.length; i++){//for each line
var line = lines[i].replace(/\s{2,}/g, ' ').split(' ');//collapse white spaces and split into an array of values
if( !dict[line[0]]) dict[line[0]] = [];//if there isn't an array to store that data yes, make one
dict[line[0]].push(parseFloat(line[1]));//append data into the coresponding key/year
dict[line[0]].push(parseFloat(line[2]));
dict[line[0]].push(parseFloat(line[3]));
}
for(var key in dict) data.push([key,dict[key]]);//at the end, loop through the object and populate an array
console.log(data);
}
}
};
xhr.send(null);
so if you use something like this:
xhr = new XMLHttpRequest();
xhr.open('GET', '/globe/raw.txt', true);
xhr.onreadystatechange = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var lines = xhr.responseText.split("\n");//split .txt file into lines
var data = [];//prepare an array to hold the end result
var dict = {};//use an Object/Dictionary to collapse data from same key/year
for(var i = 1 ; i < lines.length; i++){//for each line
var line = lines[i].replace(/\s{2,}/g, ' ').split(' ');//collapse white spaces and split into an array of values
if( !dict[line[0]]) dict[line[0]] = [];//if there isn't an array to store that data yes, make one
dict[line[0]].push(parseFloat(line[1]));//append data into the coresponding key/year
dict[line[0]].push(parseFloat(line[2]));
dict[line[0]].push(parseFloat(line[3]));
}
for(var key in dict) data.push([key,dict[key]]);//at the end, loop through the object and populate an array
window.data = data;
for (i=0;i<data.length;i++) {
globe.addData(data[i][1], {format: 'magnitude', name: data[i][0], animated: true});
}
globe.createPoints();
settime(globe,0)();
globe.animate();
}
}
};
xhr.send(null);
in the WebGL Globe experiment running on a server you will see your data.

Categories