1

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?

3
  • It's not the soulution I'm looking for because I need two distinct variables for each line Commented Apr 28, 2013 at 18:53
  • 1
    Your structure is not clear. My understanding 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. Commented Apr 28, 2013 at 18:56
  • OK thank you. I didn't create the file so I've just checked it and found out that your solution is good! Commented Apr 28, 2013 at 18:58

3 Answers 3

1

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].

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I split the first array, then splitting the splitted array ( XD ) gives me a multidimensional array (?) and then to retrieve the nth word and the nth number I do: globalArray[n][0] or globalArray[n][1]
1

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(' ');

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.