Capitalize the first character of all words (even when following a '-')
Your problem is an interesting one,but your solution is not a great use of regular expressions, since there's the better option of using the 'word boundary' anchor \b.

The boundary anchor matches a transition from a word, to a non-word, or vice versa. For this purpose, using the \w match to target word-characters after the \b is the right solution.

Note that the replace-function you give to the replace operation only needs the m argument now, there's no longer any sub-groups to process.

If your code was written as:

    String.prototype.capitalize = function(){
        return this.toLowerCase().replace( /\b\w/g, function (m) {
            return m.toUpperCase();
        });
    };


then you would convert-to-lowercase, then locate the first letter of any word, and convert that to uppercase.

Putting that in to action, like:



&lt;body&gt;
    &lt;input id="myInput" type="text" value="" size="50" /&gt;
  
    &lt;pre id="myOutput" style="background-color:lightgrey"&gt;type something in the box above&lt;/pre&gt;
  
    &lt;script&gt;
      
        String.prototype.capitalize = function(){
            return this.toLowerCase().replace( /\b\w/g, function (m) {
                return m.toUpperCase();
            });
        };
      
        var myInput = document.getElementById('myInput');
        var myOutput = document.getElementById('myOutput')

        myInput.addEventListener('input', function(e) {
            myOutput.innerHTML = this.value.capitalize();
        });
    &lt;/script&gt;

&lt;/body&gt;