I want to split text when length is 30 including space. My work so far:
var m = "Lorem ipsum dolor sit amet, co Lorem ipsum dolor sit amet, co Lorem ipsum dolor sit amet, co Lorem ipsum dolor sit amet, co";
var spacedM = m.split(' ');
var charCount = 0;
for(var i = 0; i < spacedM.length; i++){
charCount = charCount + spacedM[i].length + 0.5;
if(charCount <= 30 && $('#address1').text().length <= 30){
$('#address1').append(spacedM[i]+' ');
} else if(charCount > 30 && charCount <= 60 && $('#address2').text().length <= 30) {
$('#address2').append(spacedM[i]+' ');
} else if(charCount > 60 && charCount <= 90 && $('#address3').text().length <= 30) {
$('#address3').append(spacedM[i]+' ');
}
}
$('#address1').append($('#address1').text().length);
$('#address2').append($('#address2').text().length);
$('#address3').append($('#address3').text().length);
//output
Lorem ipsum dolor sit amet, co 31
Lorem ipsum dolor sit amet, co 31
Lorem ipsum dolor sit amet, co 31
It look like ok. But it kind of a hack too. Isn't it?. I welcome any suggestion to improve this solution. Since this code will be used to split address for older data to map it inside 3 fields of address. Below is my jsfiddle: https://jsfiddle.net/u11p6xx4/4/
UPDATED: I do not want split words. Because word in address can't split to 2 part if they are meant for 1 word. So it is actually splitting address when chars are less than 30 but don't split word. The chars can be 28 in length and then continue in #address2
Example address :
Blok 53-11-04 Apartment Flamingo, Keramat Jaya 2 Persiaran Gurney
Expected :
Blok 53-11-04 Apartment
Flamingo, Keramat Jaya 2
Persiaran Gurney
yourString.match(/.{30}/g)...string.substr(0, 30)then