I am attempting to create a tool that takes an input text and splits it into chunks of text at a certain # of characters. However, I need to make sure it does not split the
A more simple approach would be to split the entered text into an array of the individual words and then loop through the array and re-build the string, keeping a count of whether adding the next word in the array will put you over your max size.
Also, note that you should keep all of your form
elements inside a single form
.
Lastly, you should not use inline HTML event attributes (onclick
, etc.). That was a technique we used 20+ years ago before we had standards and best-practices and, unfortunately the use of the technique is so prolific, it just will not die the abrupt death it deserves. There are many reasons not to code this way and instead use the modern approach of doing all event handling with .addEventListener()
in a separate JavaScript.
// Don't set variables to properties of DOM elements, set them to the element
// itself so that if you ever want a different property value, you don't have to
// re-scan the DOM for the same element again.
var str = document.getElementById("user_input");
var output = document.getElementById("display");
document.getElementById("go").addEventListener("click",function(){
"use strict";
const size = 155; // Constant is more appropriate here
var words = str.value.split(/\s+/g); // Create array of all words in field
var finalString = "";
// Loop through array
for(var i = 0; i < words.length; i++){
if((finalString + " " + words[i]).length <= size){
finalString += " " + words[i];
} else {
break; // Max size exceeded - quit loop!
}
}
// Update field with correct value
output.textContent = finalString;
console.log(finalString.length);
});
textarea {
width:500px;
height:100px;
}
Text Splitter