我想获取多行字符串中的每一行文本并将其附加到一个变量。
这是我尝试解析的示例文本字符串:
约翰·大卫·多伊
2016 年 11 月 7 日星期四 07:22:19 -0500
随机文本
我希望 var x 为“John David Doe”,var y 为“Thu, 07 Nov 2016 07:22:19 -0500”,并忽略此后的任何文本。对于脚本,该文本将是动态的,因此我不一定要匹配“John David Doe”,而是专门匹配文本的第一行和第二行。我还希望每一行都是它们自己的变量而不是数组,因为我想稍后将它们传递到数组中。
最佳答案
您应该首先使用 Array.prototype.split() 将每一行放入数组中。然后使用解构赋值,您可以分配变量。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
const txt = document.querySelector('p').innerText;
const txtArr = txt.split('\n');
let [x, y] = txtArr;
console.log(x);
console.log(y);
<p>John David Doe
<br>Thu, 07 Nov 2016 07:22:19 -0500
<br>Random Text
</p>
关于javascript - 解析多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774534/