Reputation: 3506
Not sure if this is a duplicate (not sure how I'd word a search to find it for sure because my google-fu is weak today)
I have some javascript code to convert the first letter of every word to uppercase. I need to alter it so that it respects oddball capitalization that you might see in last names (e.g.: McGuire, MacGonnacle, O'Brien).
Essentially, the idea is to force the first letter of each word to be capitalized but not convert all the other letters to lowercase if entered in uppercase.
Here's the code snippet :
function properCase(str) {
str = str.toLowerCase();
return str.replace(/(\b)([a-z\WA-Z\W])/g,
function (firstLetter) {
return firstLetter.toUpperCase();
});
}
It's probably because it's the end of the day on a weekend but what modifications do I need to make?
Upvotes: 0
Views: 86
Reputation: 1069
You have most of it, just drop the str.toLowerCase();
function properCase(str) {
return str.replace(/(\b)([a-z\WA-Z\W])/g,function (firstLetter) {
return firstLetter.toUpperCase();
});
}
running properCase('mcCormick')
returns McCormick
Edit:
Taking a look at the regex, I think you probably don't need that whole expression (though it depends on your use case, as all things do)
function properCase(str) {
return str.replace(/(?:^|\s)([a-z])/,function (firstLetter) {
return firstLetter.toUpperCase();
});
}
This will uppercase the beginning of any word that starts with a letter. Ex properCase('mcCormick is *an excellent duelist')
returns "McCormick Is *an Excellent Duelist"
Upvotes: 2