javascript - 我想弄清楚如何使用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
并将其连接回字符串。您可以对每个索引执行此操作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"
推荐阅读
- sql - 如何将密码存储在需要以纯文本形式恢复的数据库中?
- azure - 集群自动缩放器未使用 ACS-Engine 在 Azure 上从 0 扩展
- c# - 不使用 GetVisualChild 从 DataGrid 获取单元格值
- php - 覆盖 Notifiable Trait Laravel 上的“email”属性
- sql-server - SQL Server:选择不同的日期加上条件和计数
- parallel-processing - 如何禁用可能卡在 MPI 中的进程
- reactjs - Material-UI Core TextField 全局设置 InputLabelProps 收缩
- javascript - iFrame 如何与其 HTML 进行通信
- angular - addControl() 方法用于在 FormGroup 中添加控件。有什么可以将 FormArray 添加到现有的 FormGroup 的吗?
- ffmpeg - FFmpeg 使用 v4l2 出错