Last active
May 30, 2022 15:37
-
-
Save bgrayburn/44fa018b94222590f618 to your computer and use it in GitHub Desktop.
A javascript function to word wrap given a long string and a max line length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var wordwrap = function(long_string, max_char){ | |
var sum_length_of_words = function(word_array){ | |
var out = 0; | |
if (word_array.length!=0){ | |
for (var i=0; i<word_array.length; i++){ | |
var word = word_array[i]; | |
out = out + word.length; | |
} | |
}; | |
return out; | |
} | |
var split_out = [[]]; | |
var split_string = long_string.split(' '); | |
for (var i=0; i<split_string.length; i++){ | |
var word = split_string[i]; | |
if ((sum_length_of_words(split_out[split_out.length-1]) + word.length) > max_char){ | |
split_out = split_out.concat([[]]); | |
} | |
split_out[split_out.length-1] = split_out[split_out.length-1].concat(word); | |
} | |
for (var i=0; i<split_out.length; i++){ | |
split_out[i] = split_out[i].join(" "); | |
} | |
return split_out.join('\n'); | |
}; | |
var test_string = "this is a long string that should be word wrapped, hopefully"; | |
console.log("the following should be wrapped"); | |
console.log(wordwrap(test_string, 20)); |
HTML
JS
function createDiv(text) {
var div = document.createElement("DIV");
div.classList.add("line");
div.innerHTML = text;
document.getElementById('wordWrap').appendChild(div);
}
function wordWrap(str, charMax) {
let arr = [];
let space = /\s/;
const words = str.split(space);
// push first word into new array
if (words[0].length) {
arr.push(words[0]);
}
for (let i = 1; i < words.length; i++) {
if (words[i].length + arr[arr.length - 1].length < charMax) {
arr[arr.length - 1] = `${arr[arr.length - 1]} ${words[i
]}`;
} else {
arr.push(words[i]);
}
}
//console.log('arr', arr);
return arr;
}
var str = 'The quick, brown fox jumped over the lazy dog';
let output = wordWrap(str, 6);
console.log(output);
output.forEach(line => createDiv(line));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var wordwrap = function(long_string, max_char){
if (long_string== null) { return " "; }
else {
};