每一行输出5个字符之后换行 js

时间:2021-04-13 12:28:23   收藏:0   阅读:0

方法1 

使用正则 (如果是汉字,此正则,每五个字换行,如果是英文字符,每十个英文,换行)

let arrX ="这是个测试字符串,这是个测试字符串"

arrX = arrX.replace(/[^\x00-\xff]/g,"$&\x01").replace(/.{10}\x01?/g,"$&\n").replace(/\x01/g,"")
 
方法2
循环遍历
let res = ""
let arrX ="这是个测试字符串,这是个测试字符串"
for(let i=0,j=1; i<arrX.length; i++, j++) {
  if(j&&j%6 === 0) {
    res += ‘<br />‘
  } else {
    res +=  arrX[i]
  }
}
document.write(res)
 
结果:
技术图片

 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!