Johan
Johan

Reputation: 35194

Add line breaks after n numbers of letters in long words

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

Upvotes: 6

Views: 6181

Answers (3)

Naor
Naor

Reputation: 24063

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!

Upvotes: 1

meouw
meouw

Reputation: 42140

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

Upvotes: 0

VisioN
VisioN

Reputation: 145398

Here is one option:

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

Upvotes: 11

Related Questions