-1

I'm trying to target the first letter of each word in a string. I'm working in JavaScript. I've found discussions for Python and PHP that don't address my problem specific to JavaScript.

str = "i'm a little tea pot"

regEx = /^.|\b[a-z]/g

I have a function that uppercases each letter the regEx finds. My result is the m after the apostrophe is capitalized. How do I avoid this?

After uppercase function: I'M A Little Tea Pot"

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128

2 Answers2

1

Capitalize first letter of every word?

var string = prompt("Enter a string");

function capitalizeFirstWord(str) {
    return str.split(/\s+/).map(function(word) {
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
    }).join(' ');
}

document.getElementById("capitalized").innerHTML =  capitalizeFirstWord(string);
<p id="capitalized"></p>

You split a string at a word boundary. As a parameter you pass in either an empty string or the whitespace character \s. This creates an array of all words in the sentence.

To get the first character, you can use word[0] or word.charAt(0). You then perform string concatenation with the rest of the string.

This gives you an entirely new array, which needs to be converted back to a string. Call the join method on this new array

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
1

You may use call-back function in str.replace.

var str = "i'm a little tea pot"
alert(str.replace(/(^|\s)([a-z])/g, function(match, group_1, group_2){return group_1 + group_2.toUpperCase()}))

And also if you want to convert the chars following the first char to lowercase then try this.

str.replace(/(^|\s)([a-z])(\S*)/g, function(x,y, z, a){return y + z.toUpperCase() + a.toLowerCase()})
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    I think this is a good answer. However I'm personally not a fan of using variable names like x, y and z. I would use something more descriptive. I also don't think the function should be created as the second parameter. However the logic behind it looks good – Richard Hamilton Jan 23 '16 at 03:13