6

我正在使用这个函数来构建一个猪拉丁语翻译器,似乎除了.trim()部分之外的一切都弄清楚了。我应该怎么做?

function ParseText() 
{

  var  myText = "asdf\n hat\n cat dog\n apple";

  var lines = myText.split("\n");
  var results = "";

  for (var i = 0, len = lines.length; i < len; i++) {
    lines[i].trim();
    var words = lines[i].split(" ");

    for (var j = 0, lenght = words.length; j < lenght; j++) {
      var word = words[j];

      if (word.charAt(0) == "a" || word.charAt(0) == "e" ||  word.charAt(0) == "i" || word.charAt(0) == "o" || word.charAt(0) == "u" || word.charAt(0) == "y")

      {
        results = results + word + "ay ";
      }else {
        var mutated = word.substring(1, word.length);
        mutated = mutated + word.charAt(0)+ "ay ";
        results = results + mutated;
      }
    }
    results = results + "\n";
  }
  return results;
}

线上lines[i].trim();似乎什么都没有发生。空格仍然成为拆分数组中的 \n 项。

我应该改变什么来删除空格?

4

2 回答 2

15

lines[i].trim();不修改当前字符串(请参阅此处的文档)。它返回一个新字符串。

如果要修剪当前字符串,则需要执行以下操作:

lines[i] = lines[i].trim();
于 2013-09-10T02:23:36.227 回答
2

根据评论,这是使用正则表达式的非常基本的猪拉丁语版本,它适用于小写字符串,但可以对其进行调整以处理混合的小写和大写:

function pigLatin(str) {
  return str
    .toLowerCase() // make sure string is lowercase
    .replace(/\b[aeiuo]\w+\b/g, '$&way') // starts with vowel
    .replace(/\b([^aeiou\s])(\w+)\b/g, '$2$1ay'); // starts with consonant
}


// Example: 
var str = 'hello world egg plant yellow';
console.log(pigLatin(str)); //=> "ellohay orldway eggway lantpay ellowyay"
于 2013-09-10T02:18:33.917 回答