我有一个像
这样的文字hello everyone. My name is PETER. hahahah ahahah ....
如果我有一个固定的宽度,我怎么能自动换行这个文本使文本变成这样:
hello everyone.
My name is
PETER. hahahah
ahahah
答案 0 :(得分:2)
您可以对行长度进行限制并迭代分割的字符串。
var string = 'hello everyone. My name is PETER. hahahah ahahah ....',
limit = 15,
result = string.split(' ').reduce(function (r, s) {
var line = r[r.length - 1] || '';
line += (line && ' ') + s;
if (r.length && line.length <= limit) {
r[r.length - 1] = line;
} else {
r.push(s);
}
return r;
}, []).join('\n');
console.log(result);
&#13;
答案 1 :(得分:0)
我会使用像:
这样的函数
const string = "hello everyone. My name is PETER. hahahah ahahah ...."
function autoLineBreaker(string, maxLength = 7) {
const tableString = string.split(' ')
let result = ""
let intermediaryLength = 0
for (let i = 0; i < tableString.length; i++) {
const currentWord = tableString[i]
if (intermediaryLength + currentWord.length > maxLength) {
result += ` ${currentWord} \n`
intermediaryLength = 0
} else {
result += ` ${currentWord}`
intermediaryLength += currentWord.length
}
}
return result
}
console.log(autoLineBreaker(string))
&#13;
如果您还热衷于ES8语法和函数编程,可以使用此函数的工厂来避免传递长度。语法是一个更进化的版本:
const string = "hello everyone. My name is PETER. hahahah ahahah ...."
const makeAutoLinebreakerES8 = length => string => {
let intermediaryLength = 0
return string.split(' ').reduce((finalString, current) => {
intermediaryLength = (intermediaryLength + current.length > length) ?
0 : intermediaryLength + current.length
return finalString + (intermediaryLength ? ` ${current}` : ` ${current} \n`)
}, "")
}
//example is a function
const exampleWithLengthSeven = makeAutoLinebreakerES8(7)
console.log("ES8 : \n" + exampleWithLengthSeven(string))
&#13;