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 Sho
Solution 1:
Here is one option:
string.match(/.{1,10}/g).join("<br/>");
Solution 2:
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!
Solution 3:
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 requirevar str = '123456789'; //your stringvar rxp = newRegExp( '(.{'+chunklen+'})', 'g' );
var str2 = str.replace( rxp, '$1<br/>' );
console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9
Post a Comment for "Add Line Breaks After N Numbers Of Letters In Long Words"