Why does my Javascript trim Function not work?

心不动则不痛 提交于 2021-02-19 01:44:25

问题


I am using this function to build a pig latin translator and seem to have everything figured out except for the .trim() part. What should I do different?

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;
}

On the line lines[i].trim(); nothing seems to happen. the whitespace still becomes a \n item in the split array.

What should I change to remove the whitespace?


回答1:


lines[i].trim(); does NOT modify the current string (see the doc here). It returns a new string.

If you want to trim the current string, then you need to do this:

lines[i] = lines[i].trim();



回答2:


As per comments, here's very basic version of pig latin using regex that works with lowercase strings but it can be adjusted to handle mixed lower and upper case:

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"


来源:https://stackoverflow.com/questions/18709663/why-does-my-javascript-trim-function-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!