const str = ` 1 21 3
4 5 6
7 8 9 `; /* 多行字符串要用反引号 */
var arr = str.split('\n'); /* 根据换行符分割 */
var res = new Array();
arr.forEach(function (item) {
/*
* 第一个replace是替换掉开头和最后的空格(\s包括空格和换行符),*表示0~n个
* 第二个replace是替换掉数字之间的1个到多个空格为1个空格,+表示1~n个
*/
res.push(item.replace(/(^\s*)|(\s*$)/g, "").replace(/\s+/g, " ").split(' '));
})
console.log(res);
[JavaScript]多行字符串转二维数组
最新推荐文章于 2023-06-11 21:49:36 发布