为什么我的 Javascript 修剪功能不起作用? [英] Why does my Javascript trim Function not work?

查看:23
本文介绍了为什么我的 Javascript 修剪功能不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

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

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

这篇关于为什么我的 Javascript 修剪功能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆