(JavaScript) 如何在不使用 - str.split(/ | | /g);

问题描述 投票:0回答:1

我的程序应该接受一个字符串并将其分成不同行的数组。字符串的格式如下所示(它没有明确的 ,只是通过回车键创建的新行)。我该如何达到我想要的结果?

    2PT 3PT FTM FTA PTS REB AST BLK STL GP
Mehmet Acikel Senior    15  —   4   9   34  —   —   —   —   10
Justin Baker Senior —   6   5   8   23  —   —   —   —   8
Saul Brauns Junior  3   3   4   4   19  6   1   1   —   11
Benjamin Derman Sophomore   1   1   —   —   5   1   —   —   1   3
Ayotunde Fagbemi Sophomore  44  —   4   13  92  16  —   1   3   14
Andrew Garrod Sophomore 1   —   —   1   2   3   —   —   —   4
Evan Oliver Junior  7   3   8   13  29  9   3   —   —   12
Shane Sampson Sophomore —   4   2   4   14  3   1   —   1   4
Zach Shirodkar  22  32  11  15  154 5   4   —   3   13
Nicholas Sikellis Senior    6   —   4   5   16  8   1   —   —   7
Jaden Simon Junior  32  28  12  16  157 8   2   —   4   14
Isaac Stein Junior • G  18  4   15  26  63  5   5   —   6   13
Dylan Wapner Senior • G 31  10  30  48  114 7   10  —   11  14
Total:  180 91  99  162 722 71  27  2   29  127


//Initialize String

const textAreaElement = document.getElementById('myTextArea');
const homeData = textAreaElement.value;

//Attempt to split String at new line, (unsuccessful as the format desired does not have //an explicit new line token such as \n)

var lines = homeData.split(/\r\n|\r|\n/g);

//Log first line to test if split worked correctly 

console.log(lines[0]);


javascript jquery split formatting format
1个回答
0
投票

您无法使用 regExp 拆分字符串来匹配

\r\n
\r
、或
n
,并且无法将拆分操作附加到匹配的子字符串或用包含在输出中的新行替换匹配的子字符串。同一时间。

  1. 虽然您可以将捕获组放入正则表达式中,以使

    split
    将捕获的值插入到输出数组中,它将它们作为新条目插入,所以

     "line1\nline2\n".split('\n');  // would produce
     ["line1, "\n", "line2", "\n"]  // not the desired format
    
  2. 如果输入文本包含用于换行的回车符,则文本字符串中没有

    \n
    字符开头 - 需要作为格式设置的一部分添加。


如何分割和格式化文本的示例:

© www.soinside.com 2019 - 2024. All rights reserved.