简体   繁体   English

删除字符串中的最后一个换行符

[英]Removing last line break in string

I have a list of names (var names) which after running some other code to add or remove names, I want to place in a list called nameupdated: 我有一个名称(变量名)列表,在运行其他代码以添加或删除名称后,我想将其放置在名为nameupdated的列表中:

var names = new Array('Alice', 'Bryan', 'Catherine', 'Douglas', 'Emma', 'Frank'); 
var name = "";
var nameupdated = "";
var text = "";

for(var i in names){
name = names[i];
  if (name == "" || name == text || typeof(name) == undefined)
  {

  }
  else{
    nameupdated = nameupdated + name + "\n";
  }
}

I can't seem to remove the last line break however I tried to manipulate the code. 我似乎无法删除最后一个换行符,但是我尝试操纵代码。 Anyone with any ideas how? 任何有任何想法的人如何?

The logic will probably be a lot clearer if you use .filter to remove the items you want to exclude, followed by .join by newlines. 如果使用.filter删除要排除的项,然后使用.join和换行符,则逻辑可能会更加清晰。 Note that array literals are generally nicer to work with than using the new Array constructor: 注意,数组文字通常比使用new Array构造函数更好:

 var text = 'foo'; var names = [ 'Alice', 'Bryan', 'Catherine', 'Douglas', 'Emma', 'Frank' ]; var nameUpdated = names .filter(name => !(name == "" || name == text || typeof(name) == undefined)) .join('\\n'); console.log(nameUpdated); 

  1. Try first If you want to remove last line break then you can do it in one line. 首先尝试如果您要删除最后一个换行符,则可以在一行中完成。
  2. Try second if you want string with new line 如果您想new line请尝试第二个

 var names = [ 'Alice', 'Bryan', 'Catherine', 'Douglas', 'Emma', 'Frank' ]; //Array with \\n var result = [...names].map((d, i) => i < names.length-1 && (name => !(name == "" || name == text || typeof(name) == undefined)) ? d+'\\n' : d); //String with new line after each element var result1 = [...names].map((d, i) => i < names.length-1 && (name => !(name == "" || name == text || typeof(name) == undefined))? d+'\\n' : d).join(''); console.log(result); console.log(result1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM