6

A have a string that can reach up to 100 characters in lenght. Is there an easy way to insert line breaks in the word every 10th letter? For example:

aaaaaaaaaaaaaaaaaaaaaaaaa

Should turn in to

aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa

I know that i can modify html with the html() method, but im not sure how to count characters and insert the tags. Thanks

Johan
  • 35,120
  • 54
  • 178
  • 293

3 Answers3

11

Here is one option:

string.match(/.{1,10}/g).join("<br/>");
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Assuming the text is inside a div or a 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 example: http://jsfiddle.net/68PvB/

Good Luck!

Naor
  • 23,465
  • 48
  • 152
  • 268
0

If you have your string in a variable you can use its replace method like this:

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
meouw
  • 41,754
  • 10
  • 52
  • 69