问题描述
我有从后端收到的长标题。如何通过在每50个字符后断开字符串并确保最后一行不会在每行上断开来使它变为多行?
我在这里检查了这个问题并回答。但是它们都没有道理。 JavaScript string newline character?
我们假设有一个很长的字符串:
const str = 'How to use Redis with Mongo DB and Node.js and .....'
如何通过使用正则表达式或字符串方法将每50个字符折断来使该标题多行成为示例?我不想使用任何循环。
解决方法
类似的事情可能起作用:
var str = 'How to use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and use Redis with Mongo DB and Node.js and'
var multiline_str = [...str.matchAll(/.{1,50}[^ ]+(?: +|$)/g)].join('<br/>');
console.log(multiline_str);
它最多计数50个字符,如果它落在单词的中间,则它将继续获取直到下一个单词,并用<br />
连接每个片段。