javascript字符串操作丢弃第一个字符

时间:2018-01-29 21:55:05

标签: javascript string

我试图抓住一个字符串中的所有单词,忽略任何以" ["开头的单词。但是,当我这样做它有效但却忽略了第一个角色?

let getText = function(data)
{
  line = "";

  for(let word of data)
  {
    if(word[0] != '[')
    {
      console.log("line: " + line);
      line += line + " ";
    }
  }
  console.log(line);
  return line;
}

我的输出是:

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   

单词是包含我想要的单词的continue字符串。最后一行是我打印出songLine,这是我的回归。

任何帮助都会很棒。谢谢!

调用功能

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(" "));
});

1 个答案:

答案 0 :(得分:2)

最后一个单词末尾的\r导致console.log()返回到行的开头,然后在它覆盖第一个字符后连接的空格。

在连接之前修剪你的单词。

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;
}
相关问题