I have to wrap my text, when it's longer then 16 characters and when there is space " " or a dash "-". Can I write it with regex or a function that is easier to read than mine below?
wrapType(str) {
if (str.length > 16) {
var p = 16;
while (p > 0 && (str[p] !== " " && str[p] !== "-")) {
p--;
}
if (p > 0) {
var left = (str.substring(p, p + 1) === "-") ? str.substring(0, p + 1) : str.substring(0, p);
var right = str.substring(p + 1);
return left + "\n" + this.wrapType(right);
}
}
return str;
}
function
? \$\endgroup\$ – 200_success Jun 14 '17 at 15:03(p > 0 && (str[p] !== " " && str[p] !== "-"))
, you can tryp=16 - str.match(/[^- ]/g).length
. But what if the string is of length 100 and there are total 40 spaces or dashes? And why have you cappedp
to 16? \$\endgroup\$ – Rajesh Jun 15 '17 at 7:52