1

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 !

4

1 回答 1

1

您可以通过用不间断空格替换这些单词之后的任何空格来防止短单词后出现换行符。这显示为普通空格,但此时不允许文本换行。例如

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

{1,3}指定长度为一到三个字母数字字符的单词。有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions。您希望根据自己的要求调整正则表达式。

我不认为这种效果在视觉上特别令人愉悦。浏览器没有非常复杂的自动换行算法。

于 2013-07-05T21:59:01.123 回答