如何使用 Javascript 组合两个 TextArea 句子组?

How to combine two TextArea group of sentences using Javascript?

我正在尝试像这样合并两个 TextArea 列表:

“我爱”(TextArea1) + “吃水果”(TextArea2)

“我爱”(TextArea1) +“玩游戏”(TextArea2)

结果:我爱吃水果

我喜欢玩游戏

通过以下代码无法根据相同的行号组合两个单独的组句。请帮忙!

代码:

function myFunction() {
  var x = document.getElementById("TextInput1").value;
  var y = document.getElementById("TextInput2").value;
  var res = x+" "+y;
     
  document.getElementById("ResultField").value = res;
}
 <textarea cols="30" id="TextInput1" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea>  
  
  <textarea cols="30" id="TextInput2" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea><br />
  
  
  
  <input id="WhiteSpaceRemove" onclick="myFunction()" style="border: 3px solid #73AD21;" type="button" value="Combine!" /><br>
  <br>
  <textarea autocomplete="off" cols="30" id="ResultField" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea><br />

默认情况下,字符串连接不适用于单行文本。它将第一个与另一个的整个文本合并。

为了逐行连接,您需要用一些分隔符(在这种情况下很可能是换行符)将每个文本区域的文本分开。

let firstLineArray = firstText.split("\n");
let secondLineArrary = secondText.split("\n");

这将为您提供每个文本区域文本的行数组。然后,您需要映射第一个数组,将每一行与另一个数组中的相应行连接起来。

let resultLineArray = firstLineArray.map((line,currentIndex)=>{
    return line +" "+ secondLineArray[currentIndex];
});

最后只需将所有行组合成一个字符串并将其分配到您希望显示的位置

let result = resultLineArray.join("\n");
resultTextarea.value = result;

示例

var resultElement = document.getElementById("ResultField");
var text1Element = document.getElementById("TextInput1");
var text2Element = document.getElementById("TextInput2");

function myFunction() {
  var x = text1Element.value;
  var y = text2Element.value;
  //split the textareas by newlines
  var xArr = x.split("\n");
  var yArr = y.split("\n");
  //if the textareas don't have matching 
  //number of lines of text abort
  if(xArr.length != yArr.length){
    resultElement.value = "Both textareas should contain the same number of rows of text";
    return;
  }
  
  //map over the array, combine lines, and finally join all into one string
  var result = xArr.map((line, index) => {
    return line + " " + yArr[index];
  }, "").join("\n");
  
  resultElement.value = result;
}
<textarea cols="30" id="TextInput1" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea>
<textarea cols="30" id="TextInput2" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea><br />
<input id="WhiteSpaceRemove" onclick="myFunction()" style="border: 3px solid #73AD21;" type="button" value="Combine!" /><br>
<br>
<textarea autocomplete="off" cols="30" id="ResultField" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea><br />