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
meouw source share