Capitalize Words in String

How can I capitalize the first letter of each word in a string using JavaScript?

You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

function titleCase(str) {   var splitStr = str.toLowerCase().split(' ');   for (var i = 0; i < splitStr.length; i++) {       // You do not need to check if i is larger than splitStr length, as your for does that for you       // Assign it back to the array       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);        }   // Directly return the joined string   return splitStr.join(' '); }
document.write(titleCase("I'm a little tea pot"));

Capitalize words in string

The shortest implementation for capitalizing words within a string is the following using ES6's arrow functions:

'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'

ES5 compatible implementation:

'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() })
// => 'Your String'

The regex basically matches the first letter of each word within the given string and transforms only that letter to uppercase:

  • \b matches a word boundary (the beginning or ending of word);
  • \w matches the following meta-character [a-zA-Z0-9].

For non-ASCII characters refer to this solution instead

'ÿöur striñg'.replace(/(^|\s)\S/g, l => l.toUpperCase())

This regex matches the first letter and every non-whitespace letter preceded by whitespace within the given string and transforms only that letter to uppercase:

  • \s matches a whitespace character
  • \S matches a non-whitespace character
  • (x|y) matches any of the specified alternatives

A non-capturing group could have been used here as follows /(?:^|\s)\S/g though the g flag within our regex wont capture sub-groups by design anyway.

Cheers!

How can I capitalize the first letter of each word in a string?

The .title() method of a string (either ASCII or Unicode is fine) does this:

>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'

However, look out for strings with embedded apostrophes, as noted in the docs.

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

Capitalise every word in String with extension function

Since you know capitalize() all you need is to split the string with space as a delimeter to extract each word and apply capitalize() to each word. Then rejoin all the words.

fun String.capitalizeWords(): String = split(" ").map { it.capitalize() }.joinToString(" ")

use it:

val s = "the quick brown fox"
println(s.capitalizeWords())

will print:

The Quick Brown Fox

Note: this extension does not take in account other chars in the word which may or may not be capitalized but this does:

fun String.capitalizeWords(): String = split(" ").map { it.toLowerCase().capitalize() }.joinToString(" ")

or shorter:

@SuppressLint("DefaultLocale")
fun String.capitalizeWords(): String =
split(" ").joinToString(" ") { it.toLowerCase().capitalize() }

How to capitalize the first letter of word in a string using Java?

If you only want to capitalize the first letter of a string named input and leave the rest alone:

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Now output will have what you want. Check that your input is at least one character long before using this, otherwise you'll get an exception.

Capitalizing words in a string using C#

Depending on how often you plan on doing the capitalization I'd go with the naive approach. You could possibly do it with a regular expression, but the fact that you don't want certain words capitalized makes that a little trickier.

You can do it with two passes using regular expressions:

var result = Regex.Replace("of mice and men isn't By CNN", @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);

This outputs Of Mice and Men Isn't by CNN.

The first expression capitalizes every letter on a word boundary and the second one downcases any words matching the list that are surrounded by white space.

The downsides to this approach is that you're using regexs (now you have two problems) and you'll need to keep that list of excluded words up to date. My regex-fu isn't good enough to be able to do it in one expression, but it might be possible.



Related Topics



Leave a reply



Submit