A method to add <br />
at ever 40th position is by using the following line:
string = string.replace(/([\S\s]{40})/g , "$1<br />");
If you want to dynamically set the position use:
var positions = 40;
var pattern = new RegExp("([\\s\\s]{" + positions + "})", "g");
string = string.replace(pattern , "$1<br />");
Explanation of the code:
- The first argument of the
replace
function is a RegExp:
- (
[\S\s]
= all non-whitespace and white-space characters = every character).
{40}
= 40 characters
- The
g
flag means: global match, ie: match every possible occurence
- The parentheses inside the RegExp means: Create a group. This group can later be referred by
$1
(first group)
- The second argument of the
replace
function contains $1<br />
. That is: replace the full match by the first group ($1
), and add <br />
to it.