首页 > 解决方案 > 我想弄清楚如何使用javascript将字符串中的列转换为行

问题描述

我正在处理的代码要求我获取字符串中的所有字符,将其分成行,然后将所有列记录回单个字符串。

我已将字符分成几行,但我无法将这些列重新记录到新行中:

let String= nodeStack.nodeValue;
// this wiil structure the text into a 8 columnns
let el=String.match(/.{1,8}/g);

for (i in el){
    let node = document.createTextNode(el[i]);
    let paraStack = document.createElement('p');
    paraStack.appendChild(node);
    stackCard.appendChild(paraStack);


    //this is to log all the columns into a single row
    //this is the part i am having issues with
    let res = node.nodeValue;

    let codMsg= [];
    res.split('\n').forEach(function(v){
        v.split('').forEach(function(v1, i){
            codMsg[i] = (codMsg [i]|| '') + v1;
        });
    });
    console.log(codMsg.join('\n')) ;
}

当前结果显示如下:

// console.log(el) gives
hertijhp
joiunjdk
njjooool

// console.log(codMsg.join('\n')) logs everything like this
h
e
r
t
i...
// instead of "hjneojrij"

标签: javascripthtmlarraysregexstring

解决方案


从一个字符串开始,并将其分成如下组:

let s= "ThisIsAReallyLongStringWithNoSpacesInItAtAll"
let groups = s.match(/.{1,8}/g);

console.log(groups)

正如您所看到的,每行最多有 8 个字符,因此最后您将需要一个长度为 8 的数组。对于特定索引处的这 8 个数组中的每一个,您都需要string[index]组中的所有值。这可以表示为一张地图:

groups.map(s => s[i]).join(''))

这会从您的组中获取每个字符串,获取元素i并将其连接回字符串。您可以对每个索引执行此操作0-8使用Array.from(或for循环 and push())并最终得到类似:

let s= "ThisIsAReallyLongStringWithNoSpacesInItAtAll"
let groups = s.match(/.{1,8}/g);

let a = Array.from({length: 8}, (_,i)  => groups.map(s => s[i]).join(''))
console.log(a)

join()undefined当我们尝试索引超过较短列的长度时,将忽略我们得到的值,从而为最后一列提供较短的字符串,例如"RnWaA"


推荐阅读