Add line breaks after n numbers of letters in long words

A has a string that can be up to 100 characters long. Is there an easy way to insert line breaks in a word every 10th letter? For instance:

aaaaaaaaaaaaaaaaaaaaaaaaa 

Must enter

 aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa 

I know that I can change html using the html () method, but I'm not sure how to count characters and insert tags. Thanks

+6
source share
3 answers

Here is one of the options:

 string.match(/.{1,10}/g).join("<br/>"); 
+10
source

Assuming the text is inside a div or span:

 <div id="myDiv">aaaaaaaaaaaaaaaaaaaaaaaaa</div> 

You can do:

 $(function() { var html=$('#myDiv').html(); var newHtml=''; for (var i=0;i<html.length;i++) { newHtml=newHtml+html[i]; if ((i+1)%10==0) {newHtml=newHtml+'<br/>';} } $('#myDiv').html(newHtml); }); 

Here is an example: http://jsfiddle.net/68PvB/

Good luck

+1
source

If you have a string in a variable, you can use its replace method as follows:

 var chunklen = 2; //the length of the chunks you require var str = '123456789'; //your string var rxp = new RegExp( '(.{'+chunklen+'})', 'g' ); var str2 = str.replace( rxp, '$1<br/>' ); console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9 
0
source

Source: https://habr.com/ru/post/916909/


All Articles