拆分长字符串成多行正则表达式错误

问题描述 投票:-2回答:2

我尝试将长字符串分割成多行输出的反应:

let text ='fooooooooooooooooooooooooooooooooooooooooooooooooooo'
let rowEnd=10;
let regxp = new RegExp(rowEnd, "g");
let lines = text.match(regxp);
text = lines.join("\n");
console.log(text);

但收到的错误:类型错误:无法读取属性空的“加入”。

我究竟做错了什么?

javascript regex reactjs
2个回答
1
投票

您需要使用正确的RegExp这是/.{10}/g

let text = "fooooooooooooooooooooooooooooooooooooooooooooooooooo";
let rowEnd = 10;
let regxp = new RegExp(`.{${rowEnd}}`, "g");
let lines = text.match(regxp);
text = lines.join("\n");
console.log(text);

0
投票

另一种方法是使用replace方法,就像这样:

let text ='0123456789abcsdbgdjb9876543210pol' ,
    rowEnd = 10 ,
    patt = new RegExp('.{' + rowEnd + '}','g') ;

console.log( text.replace(patt,'$&\n') ) ;
© www.soinside.com 2019 - 2024. All rights reserved.