每个X字符添加断行

时间:2016-11-23 14:53:13

标签: javascript

我尝试自动分解每个div内容,让我们说50个字符。为此,我有这个脚本,但它似乎不起作用。

https://jsfiddle.net/3sj2644z/4/

function breakline(e) {
    var $this = $(this);
    var length = $this.html().length;
    if(length % 50 == 0) {
        $this.val($this.html() + "\n");
}

有什么建议吗?

4 个答案:

答案 0 :(得分:3)

您可以使用long_string.replace(/(.{50})/g, "$1<br>");

执行此操作

var long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vel vestibulum orci. Vestibulum pulvinar sapien nec massa molestie volutpat. Duis iaculis arcu placerat odio tempor, vel venenatis nisi congue. Sed fermentum felis sed nulla mollis, at rhoncus velit condimentum. Phasellus luctus lorem justo, cursus tempus tortor laoreet quis. Pellentesque odio nibh, interdum vel ultrices sit amet, vestibulum vitae libero. Aenean vel porta quam. Morbi tincidunt diam vulputate, varius mi vel, interdum justo. Maecenas justo neque, mollis in ante ac, suscipit rhoncus sem.Vivamus vestibulum sapien mauris, quis mollis nunc auctor a. Phasellus rutrum turpis et rutrum semper. Aliquam tincidunt, orci quis convallis rutrum, lectus sapien vulputate dolor, in fermentum sem nisi et nisl. In consectetur purus risus, vitae tempor ante fermentum a. Integer ut accumsan nibh. Donec sagittis justo quam, sollicitudin vehicula leo dapibus vel. Maecenas a augue non mauris blandit accumsan. Vivamus semper fermentum nulla, quis laoreet velit egestas sit amet. Mauris ut euismod risus. Donec sit amet cursus sapien. Cras molestie arcu aliquet ipsum posuere volutpat vel id erat.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean justo libero, sagittis ut facilisis vel, hendrerit non dolor. Fusce egestas elit nec mauris aliquet elementum sodales in lacus. Aenean posuere, mauris quis pellentesque tristique, tellus eros vestibulum leo, in pretium arcu tellus vitae enim. Sed feugiat, ante eu molestie sodales, nunc tortor accumsan ligula, eget feugiat elit velit sed risus. Nulla feugiat libero imperdiet dictum commodo. Vivamus sit amet neque libero. Curabitur interdum nibh at purus pretium, id ornare magna aliquet. Vivamus accumsan varius laoreet. Suspendisse non ante in felis laoreet interdum sit amet eget velit. Proin cursus vulputate semper. Donec id nunc tortor. Vestibulum vulputate turpis eu dui mollis, in pretium lorem tempus.";

document.getElementById('container').innerHTML = long_string.replace(/(.{50})/g, "$1<br>");
<div id="container"></div>

答案 1 :(得分:1)

您正在执行的操作仅在整个文本包含50个字符时添加分隔线。
你应该做的是:
  - 如果长度超过50个字符,则每50个字符分割一次
- 加入&#39; \ n&#39;
以下代码会将您的字符串拆分为50个字符的行:

lines = str.match(/.{50}/g);


现在,您可以加入:

lines.join('<br>'); 

或者你可以使用一个班轮:

str.replace(/(.{50})/g, "$1<br>");

答案 2 :(得分:1)

我已经创建了一个类似于您的方法的答案。由于textg的值在textarea等于length % 50时获得0的值,因此我有textarea的换行符。我还添加了white-space pre-line

  

会破坏代码中断的行,但仍会剥离额外的空白区域。

Learn more about whitespace here

我已从您的HTML中删除了所有javascript并将其全部放在一个函数breakline()中。

&#13;
&#13;
function breakline(e) {
    var $this = $(this);			// store text area element
    var $textg = $('#textg');			// store div element
    var length = $this[0].value.length;		// get length of text within textarea
    $textg[0].textContent = $this[0].value;	// set text content of div to text of textarea
    if(length % 50 === 0) {	                // test if text in textarea is divisble by 50 with a remainder of 0 
    		$this[0].value += '\n';	        // add line break to textarea
    }
}

$('#text-g').on('input', breakline);	// changed from keyup to input since keyup will call breakline only when a key is released
&#13;
#textg {
  white-space: pre-line;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <textarea id="text-g" name="text-g" maxlength="300" placeholder="Message de copropriétée"></textarea>
</form>

<div id='textg' class='textg'></div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我试图通过手动创建数组来解决这个问题,但我必须使用以下方法来回答其他问题:

  • match()join();和
  • regexreplace()

不那么冗长,更优雅。

var chars = 50;
var withBreaks = document.getElementsByClassName('with-breaks')[0];
var withBreaksText = withBreaks.textContent;
var withBreaksTextLength = withBreaksText.length;
var withBreaksArray = [];
var j = 0;

for (var i = chars; i < (withBreaksText.length + chars); i = i + chars) {
withBreaksArray[j] = withBreaksText.substring(0,(chars + 1));
withBreaksText = withBreaksText.substring(chars + 1);
j++;
}

withBreaks.textContent = '';

for (var i = 0; i < withBreaksArray.length; i++) {
withBreaks.innerHTML += withBreaksArray[i] + '<br />';
}
<p class="with-breaks">Lorem ipsum dolor sit amet, ut alia vidit splendide qui, sit modo consetetur no. Duo eu affert vocibus argumentum. Ut mei delenit molestiae. Eum agam albucius appetere ad, eum ex debitis omnesque singulis, eu vidit concludaturque ius. Ea mei dicat partiendo, mazim aliquando sea eu, quot clita salutatus no vim. Cibo complectitur ea sed, ad prima veritus nec. Facer verear periculis eu quo, in per molestie honestatis. Quem quas persecuti cu nec. Ei tation corpora his. Amet iriure ex has, aliquam sanctus vim eu. Deserunt gubergren has cu. Dico nominavi dissentias ea his, vel te stet verear repudiare, duo quis scripta aliquam ut. Qui menandri platonem ne, eu eum abhorreant scribentur, usu etiam euismod lobortis et. His vivendo propriae ad. An nam congue suscipit consectetuer, mea te eleifend tractatos signiferumque. Nominavi sapientem salutatus no nec. Ad nisl sint ipsum his. Lorem aperiam repudiare no nec. Melius discere mea ei. Quas modus contentiones ex vim. Hinc lorem torquatos eu vim, brute intellegam ne nec, quo ne aeterno fuisset principes. Sea et eripuit gubergren, eu impetus aliquid definitiones nec, te alii wisi nam. Est indoctum qualisque eu, tantas splendide reprehendunt an pri. Sea perpetua dissentiunt definitionem at. Stet harum sit ad.</p>