Question

I'm dynamically filling a div with text using javascript. The div is at a fix width of 200px, and the text is automatically formatted to fit in that div. The text itself is in a json, and the json has no carriage return.

I would like to know if it's possible to detect the carriage returns that are automatically generated.

The reason I would like to know that is because I have more than a hundred texts, and if a carriage return is inserted after a 3/2 letter word, I need to insert it before the 3/2 letter word.

So I've looked on the forum, but all I tried didn't seem to work.

test = $("#mydiv").html();
html = test.split(/\r\n|\r|\n/g);
console.log(html.length);

It always returns a length of 1, as if it didn't recognize the carriage returns automatically inserted.

Thanks for any help will be most welcomed !

Was it helpful?

Solution

You can prevent line breaks after short words by replacing any space after those words with a non-breaking space. This displays like a normal space, but doesn't allow the text to be wrapped at this point. E.g.

mydiv.innerHTML = mytext.replace(/\b(\w{1,3})\s+/g, '$1 ');

The {1,3} specifies words of one to three alphanumeric characters in length. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions for details. You way wish to adjust the regular expression for your own requirements.

I don't think the effect is especially visually pleasing. Browsers don't have very sophisticated word-wrapping algorithms.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top