Split string at space after certain number of characters in Javascript

后端 未结 4 728
醉梦人生
醉梦人生 2020-12-16 03:28

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

4条回答
  •  离开以前
    2020-12-16 04:03

    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


提交回复
热议问题