I am trying to grab all words in a string ignoring any word that starts with "[". However when I do this it works but it ignores the first character?
let getText = function(data)
{
line = "";
for(let word of data)
{
if(word[0] != '[')
{
console.log("line: " + line);
line += line + " ";
}
}
console.log(line);
return line;
}
My output is:
Hello this is a test string
word:
word: Hello
word: Hello this
word: Hello this is
word: Hello this is a
word: Hello this is a test
word: Hello this is a test string
ello this is a test string
Where the word is the continues string containing just the words I want. The last line is me printing out songLine which is what I return.
Any help would be great. Thanks!
Calling function
const fs = require('fs');
fs.readFile('files/sample.txt', function(err, data) {
if(err) throw err;
let array = data.toString().split("\n");
let line = array[0];
//Test for one line
songLine = getLyrics(songLine.split(" "));
});
The \\r
at the end of the last word is causing console.log()
to return to the beginning of the line, and then the space that you concatenate after it overwrites the first character.
Trim your words before concatenating them.
let getLyrics = function(data)
{
songLine = "";
for(let word of data)
{
if(word[0] != '[')
{
console.log("word: " + songLine);
songLine += word.trim() + " ";
}
}
console.log(songLine);
return songLine;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.