How to remove newline whitespace from text file in Node? - javascript

I'm writing a program that gives me random song names I've input into a text file. Here's the code I have so far:
var fs = require('fs'),
path = require('path');
fs.readFile('names.txt', 'utf8', function(err, data) {
var arr = data.toString().split('\n'),
names = [];
for (var i in arr) {
if (arr[i].length !== 0) {
names.push(arr[i].trim());
}
}
console.log(names[1]);
});
I've noticed that whenever I put an odd number into the console.log() statement it returns the empty newline / whitespace. How can I fix this or remove it? Thanks for any help!

Your situation isn't entirely clear without full details, mainly the contents of the text file, but you probably meant to trim before the if.
Try like this:
for (var i in arr) {
var trimmed = arr[i].trim();
if (trimmed .length !== 0) {
names.push(trimmed);
}
}
Also, you shouldn't really for(.. in ..) in arrays (See here).
It's better if you use for(var i = 0; i < arr.length; i++) (you can keep the rest exactly as it is)

Alternatively:
var names = data.toString().split('\n').map(function(line){
return line.trim();
}).filter(Boolean);

Related

Matching anagrams and pushing to an array

I have a given word, that I want to match against a given list of words, mainList, and establish which words of that given list are anagrams of the given word, and add them to another list, subList.
I feel like my method to do this is fine, but it returns an unexpected result.
For example...
var word = 'master';
var mainList = ['stream', 'pidgeon', 'maters'];
var subList = [];
Then I take the word, split to an array of letters, alphabetise, and join back into a string. With this string I should be able match against any possible anagrams (which I will covert in the same way).
var mainSorted = [];
for (i = 0; i < word.length; i++) {
mainSorted = word.split('').sort().join();
}
This is where it goes wrong. I loop through the mainList array trying to establish if a given item, when converted, matches the original. If so, I want to push the word to the subList array.
for (var i = 0; i < mainList.length; i++) {
var subSorted = mainList[i].split('').sort().join;
if (mainSorted === subSorted) {
subList.push(mainList[i])
}
}
return subList;
...and the value I expect to see for subList is: ['stream', 'maters']
Yet I am returned an empty array instead.
I've gone through this so many times and I cannot see what's going wrong, would really appreciate some help!
Also, I'm aware there's probably more eloquent methods to do this (and I welcome any suggestions) but primarily I want to see where this is going wrong.
Thanks in advance.
You forgot () at the end of join
var subSorted = mainList[i].split('').sort().join;
should be
var subSorted = mainList[i].split('').sort().join();
One non-issue is
for (i = 0; i < word.length; i++) {
mainSorted = word.split('').sort().join();
}
doesnt need to be in a loop
mainSorted = word.split('').sort().join();
alone suffices
as a bonus, here's a tidier way of doing what you are doing
var word = 'master';
var mainList = ['stream', 'pidgeon', 'maters'];
var mainSorted = word.split('').sort().join();
return mainList.filter(function(sub) {
return sub.split('').sort().join() == mainSorted;
});

Replacing custom characters during string.split()

I have a fairly large javascript/html application that updates frequently and receives a lot of data. It's running very quickly and smoothly but I need to now introduce a function that will have to process any incoming data for special chars, and I fear it will be a lot of extra processing time (and jsperf is kinda dead at the moment).
I will make a request to get a .json file via AJAX and then simply use the data as is. But now I will need to look out for strings with #2C (hex comma) because all of the incoming data is comma-separated values.
in File.json
{
names: "Bob, Billy",
likes : "meat,potatoes
}
Now I need
{
names: "Bob, Billy",
likes : "meat#2Cbeear#2Cwine,potatoes
}
where #2C (hex for comma) is a comma within the string.
I have this code which works fine
var str = "a,b,c#2Cd";
var arr = str.split(',');
function escapeCommas(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf("#2C") !== -1) {
var s = arr[i].replace("#2C", ',');
arr[i] = s;
}
}
return arr;
}
console.log(escapeCommas(arr));
http://jsfiddle.net/5hogf5me/1/
I have a lot of functions that process the JSON data often as
var name = str.split(',')[i];
I am wondering how I could extend or re-write .split to automatically replace #2C with a comma.
Thanks for any advice.
Edit: I think this is better:
var j = {
names: "Bob, Billy",
likes : "meat#2Cpotatoes"
};
var result = j.likes.replace(/#2C/g, ',');
// j.likes.replace(/#2C/ig, ','); - if you want case insensitive
// and simply reverse parameters if you want
console.log(result);
This was my initial approach:
var j = {
names: "Bob, Billy",
likes : "meat,potatoes"
}
var result = j.likes.split(",").join("#2C")
console.log(result);
// meat#2Cpotatoes
Or if you have it the reverse:
var j = {
names: "Bob, Billy",
likes : "meat#2Cpotatoes"
}
var result = j.likes.split("#2C").join(",")
console.log(result);
// meat,potatoes
[Updated to reflect feedback] - try at http://jsfiddle.net
var str = 'a,b,c#2Cd,e#2Cf#2Cg';
alert(str.split(',').join('|')); // Original
String.prototype.native_split = String.prototype.split;
String.prototype.split = function (separator, limit) {
if ((separator===',')&&(!limit)) return this.replace(/,/g,'\0').replace(/#2C/gi,',').native_split('\0');
return this.native_split(separator, limit);
}
alert(str.split(',').join('|')); // Enhanced to un-escape "#2C" and "#2c"
String.prototype.split = String.prototype.native_split;
alert(str.split(',').join('|')); // Original restored
Couple minor tangential notes about your function "escapeCommas": this function is really doing a logical "un-escape" and so the function name might be reconsidered. Also, unless it is your intention to only replace the first occurence of "#2C" in each item then you should use the "g" (global) flag, otherwise an item "c#2Cd#2Cde" would come out "c,d#2Ce".

How to use a regexp to replace each item in an array using javascript

I'm a beginner with javascript, and after searching I am still running into an error with this part of my code.
I have an array:
var choices = [ '$5/hr', '$6/hr', '$7/hr', '$10/hr' ];
And I want to use a regular expression to return the array as integers so I can use it for further calculations. I know that replace only works on strings and not an array so I have tried the following:
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
EDIT: Apparently the issue is somewhere else in my code. Maybe this needs to be wrapped in another function?
Here is the function that this resides in. This function receives an array as a value and will calculate an average using the array received and the choices array which I cannot convert to integers.
// Choice values
var ul = document.getElementById('Results');
var choices = [];
// Get li element choices
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeName == "LI") {
choices.push(ul.childNodes[i]);
}
}
// Strip the last element in array since it is the result container.
choices.splice(-1,1);
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
Thanks!
The issue is that you are pushing the nodes in your array, not their text content. Try this instead:
choices.push(ul.childNodes[i].textContent)
or:
choices.push(ul.childNodes[i].childNodes[0].nodeValue)

Storing part of regex using javascript match

I want to find all #tags in a piece of text (using javascript) and use them. The regex myString.match(/#\w+/g) works, but then I also get the #. How can I get only the word without the #?
You can do something like this:
var code='...';
var patt=/#(\w+)/g;
var result=patt.exec(code);
while (result != null) {
alert(result[1]);
result = patt.exec(code);
}
The ( and ) denote groups. You can then access these groups and see what they contain. See here and here for additional information.
var result = myString.match(/#\w+/g);
result.forEach(function (word, index, arr){
arr[index] = word.slice(1);
});
Demo
Note that I'm using ES5's forEach here. You can easily replace it with a for loop, so it looks like this:
var result = myString.match(/#\w+/g);
for (var i = 0; i < result.length; i++){
result[i] = result[i].slice(1);
}
Demo without forEach
Docs on forEach

Remove element from list - JQuery/JavaScript

I have a list like this in a div:
<div id="x">5,2,3,1,4,9,8</div>
How do I simply remove a given element from this list?
JQuery or JavaScript may be used.
Please note that the numbers in the list are unique and they are coming in from a database of type int(11), they are not in any sort of order.
Any help appreciated guys...
First, get the text:
var text=$("#x").text();
Then split it:
var items=text.split(',');
If there's no items, you'll have an empty string as the only element of the array. If so, empty the array:
if(items.length==1&&items[0]=="") {
items=[];
}
Now convert everything to an integer: (note that this step isn't actually required, but if you're doing anything else with items, it's nice to have)
items=items.map(function(str) { return parseInt(str, 10); });
Put the item you want to remove in a variable:
var itemToRemove=3;
Find that in the array:
var index=items.indexOf(itemToRemove);
If it was found, splice it out of the array:
if(index!==-1) {
items.splice(index, 1);
}
Join the items back together:
text=items.join(',');
Put it back in the element:
$("#x").text(text);
Try this with toRemove equal to 5, 3, or 8 to see that it works for all cases:
var toRemove = 3; // the number you want to remove
$('#x').text($('#x').text().replace(new RegExp(toRemove + ',?'
+ '|,?' + toRemove + '$'), ''));
See example →
Using jQuery's grep-method may be an option too:
var toRemove=1;
$('#x').text( $.grep($('#x').text().split(','),
function (a) { return a != toRemove; }).join(','));
To remove multiple items:
var toRemove=[1,8,3];
$('#x').text( $.grep($('#x').text().split(','),
function (a) { return $.inArray(Number(a),toRemove)<0; })
.join(','));
(But I would prefer a RegExp-solution, it should be much faster)
This is a simple solution that just requires jquery.
function removeFromDiv(which)
{
var data = $("#x").html();
data_arr = data.split(",");
for (var i = 0; i < data_arr.length; i++)
{
if (data_arr[i] == which)
{
data_arr.splice(i, 1);
data = data_arr.join(",");
}
}
$("#x").html(data);
}
then simply run:
removeFromDiv("4");
Doesn't really need to be much harder than this:
function removeIndexFromX(index) {
// Build array from comma-delimited content
var arr = $("#x").text().split(',');
// Remove index (zero-based)
arr.splice(index, 1);
// Replace
$("#x").text(arr.join(','));
}
function removeNumberFromX(num) {
var arr = $("#x").text().split(',');
for (var i = 0; i < arr.length; i++) {
if (arr[i] === num) {
arr.splice(i, 1);
}
}
$("#x").text(arr.join(','));
}
The benefit of split and join is that you can use those to manage delimiters (e.g. commas) for you.

Categories