Javascript:将 textarea 转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2299604/
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-08-22 23:40:14  来源:igfitidea点击:

Javascript: Convert textarea into an array

javascriptarraysend-of-line

提问by Matrym

How would you go about breaking up a textarea value into an array, based on the end of line separation? Use of jQuery is cool by me...

您将如何根据行尾分隔将 textarea 值分解为数组?jQuery 的使用对我来说很酷...

回答by Daniel Vassallo

This should work (tested in Firefox and Google Chrome):

这应该有效(在 Firefox 和 Google Chrome 中测试):

var arrayOfLines = $('#textAreaID').val().split('\n');

回答by KIM Taegyoon

Cross-platform way:

跨平台方式:

var area = document.getElementById("area");             
var lines = area.value.replace(/\r\n/g,"\n").split("\n");

回答by Eric

var stringArray = document.getElementById('textarea').value.split('\n');

回答by Dexygen

I like the "cross-platform way" answer best (https://stackoverflow.com/a/32240738/34806) as I've grappled with input from a Mac in the past. Nevertheless I think mostof the existing answers could benefit from an additional step.

我最喜欢“跨平台方式”的答案(https://stackoverflow.com/a/32240738/34806),因为我过去曾处理过来自 Mac 的输入。尽管如此,我认为大多数现有答案都可以从额外的步骤中受益。

Specifically, what if some lines are empty? The following will filter out such lines so that we wind up with a "compact" array rather than a "sparse" one (or at least, rather than one with elements containing no values)

具体来说,如果某些行是空的怎么办?下面将过滤掉这样的行,以便我们得到一个“紧凑”数组而不是一个“稀疏”数组(或者至少,而不是一个元素不包含值的数组)

var area = document.getElementById("area");             
var lines = area.value.replace(/\r\n/g,"\n").split("\n").filter(line => line);

回答by Yasser Shaikh

You could try this function :

你可以试试这个功能:

function textToArray(){
  var someArray = [];    
  var nameList = $("#txtArea").val();

  $.each(nameList.split(/\n/), function (i, name) {     

      // empty string check
      if(name != ""){

          someArray.push(name);

      }        
});

taken from : CONVERT TEXTAREA CONTENT TO AN ARRAY USING JQUERY

取自:使用 JQUERY 将文本区域内容转换为数组

回答by fatih bülbül

This method worked well:

这个方法效果很好:

var textArea = document.getElementById("textAreaId");
var arrayFromTextArea = textArea.value.split(String.fromCharCode(10));