【问题标题】:I am trying to figure out how to convert columns in a string to row using javascript我想弄清楚如何使用javascript将字符串中的列转换为行
【发布时间】:2019-11-04 20:58:51
【问题描述】:

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

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

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"

【问题讨论】:

  • 欢迎来到 SO!请为您的示例提供输入
  • 您可以使用任何输入值进行测试
  • 其实我做不到,就像stackCard is not defined。我想说的是,您的代码应该是可重现的,以便其他 SO 用户对其进行检查
  • 阅读后请检查问题中的代码:How to create a Minimal, Reproducible Example.

标签: javascript html arrays regex string


【解决方案1】:

从一个字符串开始,然后像你一样把它分成几组:

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 并将其连接回字符串。您可以使用Array.from(或for 循环和push())对每个索引0 - 8 执行此操作,并最终得到类似:

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多