muklah
muklah

Reputation: 865

find words that start with specific letter

I'm trying to read file.txt with some content like this:

jone sia alex jad

and using node js I want to find the words that start with letter j this is what I write:

let fs = require('fs');

fs.readFile('./file.txt', (err, info)=>{
    let j;
    let con = 0;
    console.log(err)
    if(err) return;
    for (j=0; j < info.length; ++j)
    if (info[j] == 10)
    con++;
    console.log(con)
    if(info.indexOf('j') > -1){
        console.log(info.toString())
       }
})

I want to print the number of lines in text file and the words that start with letter j but the counter result is 3 while it should be 4 and it prints all info:

jone
sia
alex
jad

while it should print jone and jad only

how solve this

Upvotes: 0

Views: 539

Answers (4)

Oliver
Oliver

Reputation: 530

All these answers are incredibly over-complicated.

Simply iterate through all words and check if it start with the letter:

for (const word of wordList.split("\n")) {
    if (word.startsWith("j")) console.log(`${word} start with the letter j`);
}

Upvotes: 1

SakoBu
SakoBu

Reputation: 4011

Here is your file.txt:

jone
sia
alex
jad

And here is the code:

const fs = require('fs');

const output = fs
  .readFileSync('file.txt', 'utf8')
  .trim()
  .split('\n')
  .filter(word => word.includes('j'));

console.log(output);

This will get you everything that includes 'j'

If you want something that will start with j you can write your own filter function like so:

const fs = require('fs');

const output = fs
  .readFileSync('file.txt', 'utf8')
  .trim()
  .split('\n');

function filter(names, index, letter) {
  return names.filter(word => word.charAt(index) === letter);
}

console.log('Length of originanl list: ', output.length);
console.log('Filtered List: ',  filter(output, 0, 'j'));
console.log('Length of filtered list: ',  filter(output, 0, 'j').length);

Live Demo Here

Upvotes: 1

Akrion
Akrion

Reputation: 18515

You can use the readline build in core module and do something like this:

var rl = require('readline'), fs = require('fs')

var lineReader = rl.createInterface({ input: fs.createReadStream('file.txt') })

lineReader.on('line', function (name) {
  if(name.startsWith('j'))
    console.log(name)
})

See it working here

Upvotes: 2

shuk
shuk

Reputation: 1823

I suggest using the regular expressions approach.

info should be of type string, therefore it is possible for you to use the String.prototype function match(), like so:

let matches = info.match(expression);

or in your case: let matches = info.match(/\bj\w+/g); (example)

you can use regex to detect how many lines the text files has by detecting how many line breaks you have in your raw data (if possible):

let lines = info.match(/\n/g).length + 1; (example)

Upvotes: 1

Related Questions