Wrap Text
Audience Level
Beginner and above
Summary
Inserts line breaks into a continuous string in order to wrap it at a certain number of characters per line. Designed not to add linebreaks in the middle of words! Particularly useful when combined with email-sending scripts.
Example
Invoke as: "getWrapText(string, wrapWidth)" where "wrapWidth"
is usually "72" and indicates the maximum number of characters in each line of
the text.
Source Code
/*
Function: getWrapText()
Description: Inserts line breaks into a continuous string in order to wrap it at a certain number
of characters per line. Designed not to add linebreaks in the middle of words!
Returns: Exception if critical error occurs
History:
20030928 1459BST v1 Andrew Urquhart Created
*/
function getWrapText(str, wrapWidth) {
try {
// Kill carriage returns and split by newlines:
var sections = String(str).replace(/\r/g,"").split("\n");
var result = "";
for (var i in sections) {
var newLine = "";
var words = sections[i].split(" ");
for (var j=0; j<words.length; ++j) {
var word = words[j];
if ((newLine + word).length >= wrapWidth) {
result += newLine.substr(0,newLine.length-1) + "\r\n";
newLine = word + " ";
}
else {
newLine += word + " ";
}
}
if (newLine != "") {
// Final line may not be exactly wrapWidth chars long, so may
// not have been concatenated during final loop, if so add it now.
result += newLine + "\r\n";
}
}
return result;
}
catch (err) {
throw new Error(err.number, "getWrapText(): Failed with parameters wrapWidth=\"" + wrapWidth + "\" and a string \"str\" of length=\"" + str.length + "\". Message = " + err.description);
}
}
Function: getWrapText()
Description: Inserts line breaks into a continuous string in order to wrap it at a certain number
of characters per line. Designed not to add linebreaks in the middle of words!
Returns: Exception if critical error occurs
History:
20030928 1459BST v1 Andrew Urquhart Created
*/
function getWrapText(str, wrapWidth) {
try {
// Kill carriage returns and split by newlines:
var sections = String(str).replace(/\r/g,"").split("\n");
var result = "";
for (var i in sections) {
var newLine = "";
var words = sections[i].split(" ");
for (var j=0; j<words.length; ++j) {
var word = words[j];
if ((newLine + word).length >= wrapWidth) {
result += newLine.substr(0,newLine.length-1) + "\r\n";
newLine = word + " ";
}
else {
newLine += word + " ";
}
}
if (newLine != "") {
// Final line may not be exactly wrapWidth chars long, so may
// not have been concatenated during final loop, if so add it now.
result += newLine + "\r\n";
}
}
return result;
}
catch (err) {
throw new Error(err.number, "getWrapText(): Failed with parameters wrapWidth=\"" + wrapWidth + "\" and a string \"str\" of length=\"" + str.length + "\". Message = " + err.description);
}
}