我尝试将长字符串分割成多行输出的反应:
let text ='fooooooooooooooooooooooooooooooooooooooooooooooooooo'
let rowEnd=10;
let regxp = new RegExp(rowEnd, "g");
let lines = text.match(regxp);
text = lines.join("\n");
console.log(text);
但收到的错误:类型错误:无法读取属性空的“加入”。
我究竟做错了什么?
您需要使用正确的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);
另一种方法是使用replace
方法,就像这样:
let text ='0123456789abcsdbgdjb9876543210pol' ,
rowEnd = 10 ,
patt = new RegExp('.{' + rowEnd + '}','g') ;
console.log( text.replace(patt,'$&\n') ) ;