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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
HTML
JS