我不想只是为了断字而将库添加到我的页面中。然后,我在下面提供了一个简单的功能,希望对人们有所帮助。
(它被打破了15个字符,并且在两者之间加上了“­”,但是您可以在代码中轻松地对其进行更改)
BreakLargeWords = function (str)
{
BreakLargeWord = function (word)
{
var brokenWords = [];
var wpatt = /\w{15}|\w/igm;
while (wmatch = wpatt.exec(word))
{
var brokenWord = wmatch[0];
brokenWords.push(brokenWord);
if (brokenWord.length >= 15) brokenWords.push("­");
}
return brokenWords.join("");
}
var match;
var word = "";
var words = [];
var patt = /\W/igm;
var prevPos = 0;
while (match = patt.exec(str))
{
var pos = match.index;
var len = pos - prevPos;
word = str.substr(prevPos, len);
if (word.length > 15) word = BreakLargeWord(word);
words.push(word);
words.push(match[0]);
prevPos = pos + 1;
}
word = str.substr(prevPos);
if (word.length > 15) word = BreakLargeWord(word);
words.push(word);
var text = words.join("");
return text;
}
var bigText = "Why is this text this big? Lets do a wrap <b>here</b>! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
var goodText = BreakLargeWords(bigText);