Search code examples
javascriptregexspacescapitalize

Capitalize first letter and remove space in string


Got some code to capitalize the first letter of every word in a string. Can someone please help me update it so it also removes all spaces within the string once the first letters are Capped.

return function (str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1);
    });
}

Solution

  • Try this:

    var input = 'lorem ipsum dolor sit amet';
    // \w+ mean at least of one character that build word so it match every
    // word and function will be executed for every match
    var output = input.replace(/\w+/g, function(txt) {
      // uppercase first letter and add rest unchanged
      return txt.charAt(0).toUpperCase() + txt.substr(1);
    }).replace(/\s/g, '');// remove any spaces
    
    document.getElementById('output').innerHTML = output;
    <div id="output"></div>

    You can also use one regex and one replace:

    var input = 'lorem ipsum dolor sit amet';
    // (\w+)(?:\s+|$) mean at least of one character that build word
    // followed by any number of spaces `\s+` or end of the string `$`
    // capture the word as group and spaces will not create group `?:`
    var output = input.replace(/(\w+)(?:\s+|$)/g, function(_, word) {
      // uppercase first letter and add rest unchanged
      return word.charAt(0).toUpperCase() + word.substr(1);
    });
    
    document.getElementById('output').innerHTML = output;
    <div id="output"></div>