您有一个字符串“This is a test that has to be done using Javascript“。将文本从右到左分成多行,不能用连字符,其中行的最大长度为20个字符(只能在单词之间断开,下一行不能以空格开头)
"using Javascript
that has to be done
This is a test"
代码如下
function splitWordsReverse(s) {
// 切割并翻转单词
const words = s.split(' ').reverse();
const arr = [];
// 设置最大字符数
const lengthMax = 20;
// 遍历所有单词
words.forEach(item => {
if (arr[arr.length - 1] && arr[arr.length - 1].length + item.length + 1 <= lengthMax) {
arr[arr.length - 1] = item + ' ' + arr[arr.length - 1];
} else {
arr.push(item)
}
});
return arr.join('\n');
}
const res = splitWordsReverse('This is a test that has to be done using Javascript');
console.log(res);