Thursday, 24 March 2016

JavaScript: split sentence and add line breaks

I've been using Semantic UIs form validation nigh on constantly over the past few months and apart from the ability to write my own validation rules (which is a brilliant thing by the way) I'm also impressed with the messages that get slung into the UI. The on ly problem I've had though is if the message is particularly long then it can often mess up the layout of the form. After some experimentation I discovered that adding <br/> tags added line breaks within the message. I'm using this an awful lot so I decided to write a simple function which takes a string and splits it on words. It's a wee bit fuzzy so perhaps could do with a wee bit of tidying, but it works for my purposes:

function addBr(sentence, letters, seperator){
    letters = letters || 25;
    seperator = seperator || "<br/>"
    words = sentence.trim().split(" ");
    var returnString = "";
    var line = "";
    while(words.length > 0){
        if(line.length < letters){
            if(~~line.length){
                line += " " + words.shift();
            }else{
                line += words.shift();
            }
        }else{
            returnString += line + seperator;
            line = "";
        }
    }
    if(line !== ""){
        returnString += line;
    }    
    return returnString;
}

Here's a working JSFiddle.