-1

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);
    });
}
Richy
  • 147
  • 2
  • 12
  • [This](http://codereview.stackexchange.com/questions/77614/capitalize-the-first-character-of-all-words-even-when-following-a) explains how to capitalize every first letter. – Clever Programmer Jan 18 '16 at 11:23
  • 1
    Possible duplicate of [Capitalize the first letter of string in JavaScript](http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript) – Universal Electricity Jan 18 '16 at 11:48

4 Answers4

5

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>
jcubic
  • 51,975
  • 42
  • 183
  • 323
1

You can use a simple helper function like:

return function (str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1);
    }).replace(/\s/g, "");
}
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
0

Page has a nice example of how to capitalize each word in a string in JavaScript: http://alvinalexander.com/javascript/how-to-capitalize-each-word-javascript-string

0

As an alternative you can split the string on the space, capitalize each word and then join them back together again:

"pascal case".split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1) ).join('')
JayChase
  • 9,520
  • 2
  • 40
  • 46