javascript – regex split string at specific length and ignore incomplete word
Why can’t you just use regex? Like:
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 n = m.match(/.{31}/g);
$('#address1').append(n[0]);
$('#address2').append(n[1]);
$('#address3').append(n[2]);
$('#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
But what happens if there is a 4th group matched? Do you just ignore everything from the ((31*3)+1)-th character?
Update:
Try using this regex /[^\W].{1,30}(?:\s|$)/g, you’ll still need to improve it but it should get you started:
var m = "Blok 53-11-04 Apartment Flamingo, Keramat Jaya 2 Persiaran Gurney";
var n = m.match(/.{1,30}(?:\s|$)/g); // or /[^\W].{1,30}(?:\s|$)/g
$('#address1').append(n[0]);
$('#address2').append(n[1]);
$('#address3').append(n[2]);
// output
// Blok 53-11-04 Apartment
// Flamingo, Keramat Jaya 2
// Persiaran Gurney
You can expirement here: regex101.com/r/TIRa6L/2
If you wan’t a more reliable approach try a so called “address verification api”. Something like:
It should be able to parse a 1 line address and convert it into the correct multi-line format.
Read more here: Source link
