为什么我的 Javascript 修剪功能不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18709663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:57:15  来源:igfitidea点击:

Why does my Javascript trim Function not work?

javascriptwhitespacetrimremoving-whitespace

提问by jth41

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?

我正在使用此功能来构建一个猪拉丁语翻译器,并且似乎已经弄清楚了除了.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;
}

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

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

What should I change to remove the whitespace?

我应该更改什么以删除空格?

回答by jfriend00

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

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

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

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

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

回答by elclanrs

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, 'ay'); // starts with consonant
}


// Example: 
var str = 'hello world egg plant yellow';
console.log(pigLatin(str)); //=> "ellohay orldway eggway lantpay ellowyay"