簡體   English   中英

我想弄清楚如何使用 javascript 將字符串中的列轉換為行

[英]I am trying to figure out how to convert columns in a string to row using 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"

從一個字符串開始,然后像你一樣把它分成幾組:

 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM