如何在 Javascript 中按行和列拆分字符串

我有一个带有两个定界符的下面的字符串。“|” 用于行,“*”用于列。我想知道如何在 JS 代码中按行和列拆分这些字符串

"1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|"

慕莱坞森
浏览 184回答 6
6回答

ITMISS

您可以使用 split 函数两次来创建嵌套数组:let str = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";let arr = str.split("|").map(r => r.split("*"));console.log(arr);

MMTTMM

也许有点过时,但同样有效var a ="1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00";var b = a.split("|");var c = [];for (i = 0; i < b.length; i++) {&nbsp; &nbsp; &nbsp;c[i] = b[i].split("*");}

交互式爱情

您可以使用多个 delemiter 进行拆分。const str = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|"const splitStr = str.split(/\*|\|/);console.log(splitStr);

郎朗坤

如果您想一次过一遍,这应该创建一个表示数组/列的嵌套数组结构。它也很粗糙,可能会稍微简化一下。const fullStr = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";const arr = [[]];for(let i = 0, str = ''; i < fullStr.length; i++){&nbsp; if(fullStr[i] == '*') {&nbsp; &nbsp; arr[arr.length - 1].push(str);&nbsp; &nbsp; str = '';&nbsp; &nbsp; continue;&nbsp; }&nbsp; if(fullStr[i] == '|') {&nbsp; &nbsp; arr[arr.length -1].push(str);&nbsp; &nbsp; // you could wrap this push statement in an if to determine if you are at the end of the string.&nbsp; &nbsp; arr.push([]);&nbsp; &nbsp; str = '';&nbsp; &nbsp; continue;&nbsp; }&nbsp; str += fullStr[i];&nbsp;&nbsp;}console.log(arr);

qq_笑_17

这里已经有很多好的答案——这将返回一个具有行/列属性的单元格对象数组:let mystring = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";let cells = mystring.split("|");let results = [];for (let i = 0; i < cells.length; i++) {&nbsp; let cell = cells[i];&nbsp; let cellData = cell.split("*");&nbsp; results.push({&nbsp; &nbsp; row: cellData[0],&nbsp; &nbsp; col: cellData[1]&nbsp; })}console.log(results);

牧羊人nacy

const input = "1264.75|24936.00|38230.76|48329.75|53106.25|63442.00|75122.50|1077.00|117581.00|127573.25|133509.00|215246.50|244181.00|254961.25|52*34.00|"// The filter is for removing empty rowsinput.split("|").filter(val=>!!val).map(val => val.split("*").map(res=>parseFloat(res)))结果会像[[1264.75],[24936],[38230.76],[48329.75],[53106.25],[63442],[75122.5],[1077],[117581],[127573.25],[133509],[215246.5],[244181],[254961.25],[52,34]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript