Sunny-117/js-challenges

多行字符串转二维数组

Sunny-117 opened this issue · 3 comments

const str = ` 1 21    3
4 5  6
7   8 9 `;        /* 多行字符串要用反引号 */
var arr = str.split('\n'); /* 根据换行符分割 */
const str = ` 1 21    3
4 5  6
7   8 9 `; /* 多行字符串要用反引号 */
var arr = str.split("\n"); /* 根据换行符分割 */
const res = [];
for (const subarr of arr) {
  let line = subarr.split(" ").filter((e) => e !== " " && e !== '');
  res.push(line);
}
console.log(res);
const arr = str.split('\n'); /* 根据换行符分割 */
const res = [];
for (const subarr of arr) {
  let line = subarr.trim().split(/\s+/g)
  res.push(line);
}
console.log(res);
var str = `line1 part1 part2
line2 part1 part2
line3 part1 part2`;

var arr = str.split('\n').map(function(line) {
    return line..trim().split(/\s+/g);
});

console.log(arr);