Javascript wrap text with conditions 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 &gt; 16) {
            var p = 16;
            while (p &gt; 0 &amp;&amp; (str[p] !== " " &amp;&amp; str[p] !== "-")) {
                p--;
            }
            if (p &gt; 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;
}
Some minor changes to improve readability:


It's generally considered better practice to use str.charAt(0) instead of str[0] (even though str[0] often outperforms .charAt()).
Simplify the while condition and have it only check if p &gt; 0; the character checks can be done inside the loop. This also lets you eliminate the if (p &gt; 0) check.
Add some comments.


You could also incorporate p-- into your while loop (so it would read while (p-- &gt; 0) { but that wouldn't improve readability.

wrapType(str) {
        if (str.length &gt; 16) {
            // if string is longer than 16 characters
            var p = 16;
            while (p &gt; 0) {
                // loop through the string and check each char
                if ((str.charAt(p) === " " || str.charAt(p) === "-") {
                    // if a dash or space is found, wrap the string
                    var left = (str.charAt(p) === "-") ? str.substring(0, p + 1) : str.substring(0, p);
                    var right = str.substring(p + 1);
                    return left + "\n" + this.wrapType(right);    // return the wrapped string
                }
                p--;
            }
        }
        return str;    // return the original string
}


If you wanted to take it further, you could create a small function to do the character-checking called breakHere or something similar that would return true if it found a dash or space, and false otherwise.  Then for your if checks, instead of checking for both the dash and space, you could just do something like if (breakHere()) { ... } which would make for slightly longer code but might make it easier for someone new to follow what's going on.  You could even have that function return the value itself, so you could call newStr = breakHere(); and newStr would either be assigned the wrapped string (if a dash or space was found) or the original string (str).  That would allow you to combine your two separate return statements into one -- return newStr.