Reputation: 1118
I have a .txt file with this structure:
chair 102
file 38
green 304
... ...
It has 140.000 elements.
Before introducing the numbers I used javascript and jQuery:
$(function () {
$.get('/words.txt', function (data) {
words = data.split('\n');
});
But because I have now numbers how could I treat separately the strings and the numbers?
Upvotes: 1
Views: 2235
Reputation: 34038
An efficient way of handling this problem is to replace all the line breaks with spaces, then split the resulting string by the spaces. Then use what you know about the position of the elements to determine whether you're dealing with a number or a string:
var resultArr = data.replace(/\n/g, " ").split(" ")
for(var i = 0; i < resultArr.length; i++) {
if(i % 2) {
// even indexes represent the word
console.info("word = " + resultArr[i]);
} else {
// odd indexes represent the number
console.info("number = " + resultArr[i]);
}
}
Depending on whether or not there's a line break at the end of the set, you may need to handle that case by looking for an empty string.
Upvotes: 1
Reputation: 5060
you could split at each new line and then split each element at space, but this will gives you array of array of words .
you could replace line with space and then split at space ie:
words = data.replace(/\n/g,' ').split(' ');
Upvotes: 1
Reputation: 31131
Since this helped, I'll post as an answer:
Your format is <word><space><num>\n
You split on new line, so now you have an array of <word><space><num>
which you should be able to split on space.
Then you can get the word part as myarray[0]
and the number part as myarray[1]
.
Upvotes: 1