Ezhno Ezhno - 12 days ago 6
Javascript Question

Break Line each X characters if it's a space, if not wait for a space

I have this working script that is breaking the line each 79 characters. I would like to add a condition that it does only break the line if the 79th character is a space, if not, then it will break at the next space inputed. (So that the words will not be broke)

Here is the function I have currently. (I don't know how to add this condition in the expression)

function myFunction() {
var long_string = document.getElementById('textg').innerHTML;
document.getElementById('textg').innerHTML = long_string.replace(/(.{79})/g, "$1<br>");
}

Answer

This should do the trick:

var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed aliquet feugiat enim. Nam viverra sapien quis nisi consequat, nec viverra ligula tempus. Pellentesque sed diam id velit malesuada pellentesque. Vivamus nec condimentum purus. Suspendisse purus lacus, elementum non feugiat molestie, volutpat nec nisl. Vivamus mauris eros, pulvinar eu velit vitae, hendrerit venenatis velit. In accumsan nec lacus eget aliquet. Integer ullamcorper accumsan lacinia. Sed eleifend dignissim libero. Aenean sodales imperdiet ipsum, ut vulputate ante accumsan sit amet. Nunc mollis tristique finibus. Donec pellentesque orci nec ante efficitur scelerisque. Cras ullamcorper euismod sem in pretium. Morbi felis turpis, venenatis sit amet erat mattis, consectetur commodo nisi. Aliquam varius ultrices orci eget tristique.";

var broken = str.replace(/(.{79}[^ ]+ )/g, "$1<br />");

document.getElementById('result').innerHTML = broken;
<pre id="result"></pre>

The magic is in this regex:

/(.{79}[^ ]+ )/g

It captures:

  • 79 characters: .{79} +
  • Anything that follows it that isn't a space: [^ ]+ +
  • The trailing space .

The replace then replaces the captured section with "that" + a linebreak ("$1<br />")


Note that this will result in spaces before the <br />, in the string:
enim. <br />Nam

If you want to get rid of those, move that last space out of the capture group, in the regex:

/(.{79}[^ ]+) /g