分别从文本字段中读取值

Read values from text field individually

我想单独读取文本 field/text 框中的所有值,然后将它们写入 table:

示例:

This is an example of a text I want to read out.

输出:

  1. 这个
  2. 一个
  3. 例子
  4. 一个
  5. 文本
  6. 想要
  7. 阅读
  8. 出来

如何使用循环读取文本 field/text 框? 也就是说,每当 space 出现时,新的后续值必须在新行中。

字符串:

var table = document.getElementById("table");
var phrase = "This is an example of a text I want to read out";

var words = phrase.split(" ");
for (var i = 0; i < words.length; i++) {
  var tableCol = 
  `<tr>
    <td>${i+1}:</td>
    <td>${words[i].replace(/[\.,!\?]/g," ")}<td>
  </tr>`;
  
  document.querySelector('table tbody').innerHTML += tableCol;
}
#table {
  border: 1px solid;
}

th {
  border: 1px solid;
  padding: 5px;
}
<table id="table">
  <thead>
    <th>Number:</th>
    <th>Word:</th>
  <thead>
  <tbody>

  </tbody>
</table>

输入:

var table = document.getElementById("table");
var myBtn = document.getElementById("myBtn");
var myInput = document.getElementById("myInput");

myBtn.addEventListener('click', () => {
  document.querySelector('tbody').innerHTML = '';
  var phrase = myInput.value;
  var words = phrase.split(" ");
  for (var i = 0; i < words.length; i++) {
    var tableCol = 
    `<tr>
      <td>${i+1}:</td>
      <td>${words[i].replace(/[\.,!\?]/g," ")}<td>
    </tr>`;

    document.querySelector('tbody').innerHTML += tableCol;
  }
});
input {
  margin-bottom: 10px;
  width: 300px;
  height: 25px;
}

#table {
  border: 1px solid;
}

th {
  border: 1px solid;
  padding: 5px;
}
<input id="myInput" type="text">
<button id="myBtn">Create Table</button>

<table id="table">
  <thead>
    <th>Number:</th>
    <th>Word:</th>
  <thead>
  <tbody>

  </tbody>
</table>

更短并删除标点符号

const str = `This is an example of a text I want to read out.`;

document.querySelector('table tbody').innerHTML = str.split(" ")
  .map((word,i) => `<tr><td>${i+1}:</td><td>${word.replace(/[\.,!\?]/g,"")}<td></tr>`)
  .join("");
<table id="table">
  <thead>
    <th>Number:</th>
    <th>Word:</th>
  <thead>
  <tbody>

  </tbody>
</table>