How can I split a string in JavaScript after the first space after 15 characters?

I have read the solution on this post How do I split a string at a space after a certain number of characters in javascript?

And it works to a certain point. But what I am trying to achieve is slightly different.

I have a user input which has a 40 character limit. I am taking that input and displaying it on the screen. However, I need to split the input at around 20 characters and then insert the remainder on the next line. And it is only allowed to go on 2 lines max.

UPDATE:: I should also mention here that as well as displaying the text on the front end, we also need to pass the string to our backend. But instead of sending it with the <br/>, we need to insert \n to force the new line in our backend system.

Ultimately, each line cannot be over 20 characters. However, it needs to be dynamic, so that if the user inputs a string that is 30 characters, but the space comes before the 20th character, how can I adjust it so that it splits at a space before the 20th character? – I hope that makes sense.

For example

TEXT12345 STRING46789

Should appear like this

TEXT12345

STRING46789

but, also the following

TEXT STRING ABCDEF

NEW LINE HERE

Each line needs to be a maximum of 20 characters and I can’t force hyphenation.

The below code is what I have done, but it doesn’t work well as I often get ‘undefined’ before the space. Plus, its not dynamically looking for a space before the 20 character limit

Child1Name.keyup(function(e) {

    var stringValue = Child1Name.val();

    if (stringValue.length > 19) {

      let [firstLine, secondLine] = stringValue.replace(/.{20}\S*\s+/g, "$&@").split(/\s+@/)
      
      previewChild1Name.html(firstLine + "<br/>" + secondLine);
      
    }else{

      previewChild1Name.text(stringValue);
      
    }

});

Any help here would be greatly appreciated.

>Solution :

You can write a function like below. First split your string with space and loop over it to append the word. If after appending a new word it surpasses the length then add existing word to arr and clear the current string.

Try the code below.

function getSplittedString(s, length) {
  let arr = [];
  let str = '';
  s.split(' ').forEach(x => {
    if (str !== '' && (str + ' ' + x).length > length) {
      arr.push(str);
      str = '';
    }
    str = (str + ' ' + x).trim();
  });

  if (str !== '') {
    arr.push(str);
  }

  return arr.join('<br/>')
}

console.log(getSplittedString('TEXT12345 STRING46789', 20));

Leave a Reply