Select the text you want to change to uppercase, then go to the Home tab. In the Font group, select the Change Case drop-down arrow. Choose UPPERCASE to change the selected text to all uppercase letters.
Contents
- 1 How do you make all words in a Word document capital?
- 2 How do you auto capitalize all letters in Word?
- 3 How do you capitalize without retyping in Word?
- 4 Why is shift F3 not working?
- 5 How do I turn on auto capitalization in Windows 10?
- 6 Why are all my i’s capitalized in word?
- 7 How do you capitalize all letters in word on a Mac?
- 8 How do you select all text in word?
- 9 What is the change case?
- 10 What is a toggle case?
- 11 What is upper case character?
- 12 What does Alt F4 do in Word?
- 13 What does the F10 key do?
- 14 What does Shift F7 mean?
- 15 Where is auto capitalization in settings?
- 16 How do you capitalize on a computer?
- 17 How do you auto capitalize the letter I?
- 18 How do you auto correct i to i?
- 19 Where is F3 on a Mac?
- 20 What is F3 key on Mac?
How do you make all words in a Word document capital?
Now you can simply choose “Capitalization” from the Format menu in Docs, and select one of the following: lowercase, to make all the letters in your selection lowercase. UPPERCASE, to capitalize all the letters in your selection.
How do you auto capitalize all letters in Word?
To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.
How do you capitalize without retyping in Word?
Select the text you want to change the case of, using your mouse or keyboard. On the Home tab of the Ribbon, go to the Fonts command group and click the arrow next to the Change Case button.
Why is shift F3 not working?
Shift F3 Not Working When The “Fn” Key Is Locked
2.Fn + Caps Lock. Fn + Lock Key (A keyboard key with only a lock icon on it) Press and Hold the Fn key to enable/disable.
How do I turn on auto capitalization in Windows 10?
To turn on auto-caps of the first word please follow these steps:
- Open Settings, and click/tap on Devices.
- Click/tap on Typing on the left side, and turn On (default) or Off Capitalize the first letter of each sentence under Touch keyboard on the right side for what you want. (
Why are all my i’s capitalized in word?
There are multiple reasons why everything may become capitalized in Microsoft Word: The Caps Lock button on the keyboard is turned on. One of the Shift keys on the keyboard has physically jammed. A font type has been selected that only has upper case letters.
How do you capitalize all letters in word on a Mac?
Switch between uppercase and lowercase in Word on Mac
1) Select the text, whether a single word or entire document. 2) Hold Shift and press F3. You can continue to hold the Shift key and click F3 to move through the uppercase, lowercase, and capital options until you get the one you want.
How do you select all text in word?
Select all text
- Click anywhere within the document.
- Press Ctrl+A on your keyboard to select all text in the document.
What is the change case?
A change case is used to define new requirements for a system or to modify the existing requirements of a system. Defining new requirements for a system indicate the likeliness of the change occurring and indicate the impact of that change. Example1: Change case to define new requirement.
What is a toggle case?
Toggle case is used when you want to automatically change the case of the text you have already typed. If you highlight a portion of text it will change all the lower case to uppercase and all lower case to upper case in one click. Just highlight the text and click on toggle case and it will change for you.
What is upper case character?
Uppercase characters are capital letters; lowercase characters are small letters. For example, box is in lowercase while BOX is in uppercase. The term is a vestige of the days when typesetters kept capital letters in a box above the lowercase letters.
What does Alt F4 do in Word?
Alt + F4 is a Windows keyboard shortcut that completely closes the application you’re using. It differs slightly from Ctrl + F4, which closes the current window of the application you’re viewing. Laptop users may need to press the Fn key in addition to Alt + F4 to use this shortcut.
What does the F10 key do?
F10. The F10 key will open the menu bar or similar options within most open Microsoft apps. Hitting Shift + F10 on a highlighted file, link or icon will act in the same way as a right-click.
What does Shift F7 mean?
F7. Commonly used to spell check and grammar check a document in Microsoft programs such as Microsoft Outlook, Word etc. Shift+F7 runs a Thesaurus check on word highlighted. Turns on the Caret Browsing in Mozilla Firefox.
Where is auto capitalization in settings?
Open the messaging app of your choice.
- On the on-screen keyboard, tap the gear icon.
- In the Settings menu, select “Text correction.”
- Swipe up on the Text Correction menu until you locate “Auto-capitalization.”
- Tap the slider next to “Auto-capitalization” so that it appears gray instead of blue.
How do you capitalize on a computer?
Press and hold either the left or right Shift and while continuing to hold the Shift key press the letter you want caps. Using the Shift key is the most common method of creating a capital letter on a computer.
How do you auto capitalize the letter I?
Or use Word’s keyboard shortcut, Shift + F3 on Windows or fn + Shift + F3 for Mac, to change selected text between lowercase, UPPERCASE or capitalizing each word.
How do you auto correct i to i?
How to use Auto-Correction and predictive text on your iPhone, iPad, or iPod touch
- Open the Settings app.
- Tap General > Keyboard.
- Turn on Auto-Correction. By default, Auto-Correction is on.
Where is F3 on a Mac?
The Function of Each F Key
Mac Function Keys | |
---|---|
F1 | Reduce the screen’s brightness |
F2 | Increase the screen’s brightness |
F3 | Activates Expose view, which shows you every app that’s running |
F4 | Showcases your apps or opens the dashboard for access to widgets |
What is F3 key on Mac?
Mission Control
These are the primary defaults of what function keys do on an Apple keyboard when connected to a Mac: F1 – Decrease display brightness. F2 – Increase display brightness. F3 – Open Mission Control.
What is the best approach to capitalize words in a string?
asked Feb 25, 2010 at 9:12
12
/**
* Capitalizes first letters of words in string.
* @param {string} str String to be modified
* @param {boolean=false} lower Whether all other letters should be lowercased
* @return {string}
* @usage
* capitalize('fix this string'); // -> 'Fix This String'
* capitalize('javaSCrIPT'); // -> 'JavaSCrIPT'
* capitalize('javaSCrIPT', true); // -> 'Javascript'
*/
const capitalize = (str, lower = false) =>
(lower ? str.toLowerCase() : str).replace(/(?:^|s|["'([{])+S/g, match => match.toUpperCase());
;
- fixes Marco Demaio’s solution where first letter with a space preceding is not capitalized.
capitalize(' javascript'); // -> ' Javascript'
- can handle national symbols and accented letters.
capitalize('бабушка курит трубку'); // -> 'Бабушка Курит Трубку'
capitalize('località àtilacol') // -> 'Località Àtilacol'
- can handle quotes and braces.
capitalize(`"quotes" 'and' (braces) {braces} [braces]`); // -> "Quotes" 'And' (Braces) {Braces} [Braces]
answered Sep 29, 2011 at 3:47
disfateddisfated
10.5k12 gold badges39 silver badges50 bronze badges
13
The shortest implementation for capitalizing words within a string is the following using ES6’s arrow functions:
'your string'.replace(/bw/g, l => l.toUpperCase())
// => 'Your String'
ES5 compatible implementation:
'your string'.replace(/bw/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.
user
10.9k6 gold badges23 silver badges83 bronze badges
answered Jul 22, 2016 at 15:31
IvoIvo
6,3961 gold badge25 silver badges43 bronze badges
8
function capitalize(s){
return s.toLowerCase().replace( /b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
output: «This Is The Worst String Ever»
Update:
It appears this solution supersedes mine: https://stackoverflow.com/a/7592235/104380
2
The answer provided by vsync works as long as you don’t have accented letters in the input string.
I don’t know the reason, but apparently the b
in regexp matches also accented letters (tested on IE8 and Chrome), so a string like "località"
would be wrongly capitalized converted into "LocalitÀ"
(the à
letter gets capitalized cause the regexp thinks it’s a word boundary)
A more general function that works also with accented letters is this one:
String.prototype.toCapitalize = function()
{
return this.toLowerCase().replace(/^.|sS/g, function(a) { return a.toUpperCase(); });
}
You can use it like this:
alert( "hello località".toCapitalize() );
answered Apr 15, 2011 at 15:03
Marco DemaioMarco Demaio
33.2k33 gold badges128 silver badges157 bronze badges
2
A simple, straightforward (non-regex) solution:
const capitalizeFirstLetter = s =>
s.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')
- Break the string into words Array (by space delimiter)
- Break each word to first character + rest of characters in the word
- The first letter is transformed to uppercase, and the rest remains as-is
- Joins back the Array into a string with spaces
vsync
115k56 gold badges298 silver badges391 bronze badges
answered Jan 16, 2019 at 18:08
OtmanOtman
1112 silver badges7 bronze badges
1
Ivo’s answer is good, but I prefer to not match on w
because there’s no need to capitalize 0-9 and A-Z. We can ignore those and only match on a-z.
'your string'.replace(/b[a-z]/g, match => match.toUpperCase())
// => 'Your String'
It’s the same output, but I think clearer in terms of self-documenting code.
answered Feb 25, 2019 at 8:14
Big MoneyBig Money
8,7796 gold badges24 silver badges37 bronze badges
1
Since everyone has given you the JavaScript answer you’ve asked for, I’ll throw in that the CSS property text-transform: capitalize
will do exactly this.
I realize this might not be what you’re asking for — you haven’t given us any of the context in which you’re running this — but if it’s just for presentation, I’d definitely go with the CSS alternative.
answered Feb 25, 2010 at 9:18
David HedlundDavid Hedlund
128k31 gold badges201 silver badges221 bronze badges
2
My solution:
String.prototype.toCapital = function () {
return this.toLowerCase().split(' ').map(function (i) {
if (i.length > 2) {
return i.charAt(0).toUpperCase() + i.substr(1);
}
return i;
}).join(' ');
};
Example:
'álL riGht'.toCapital();
// Returns 'Áll Right'
answered Mar 13, 2017 at 19:06
3
John Resig (of jQuery fame ) ported a perl script, written by John Gruber, to JavaScript. This script capitalizes in a more intelligent way, it doesn’t capitalize small words like ‘of’ and ‘and’ for example.
You can find it here: Title Capitalization in JavaScript
answered Feb 25, 2010 at 10:27
meouwmeouw
41.6k10 gold badges51 silver badges69 bronze badges
0
Using JavaScript and html
String.prototype.capitalize = function() {
return this.replace(/(^|s)([a-z])/g, function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
<form name="form1" method="post">
<input name="instring" type="text" value="this is the text string" size="30">
<input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();">
<input name="outstring" type="text" value="" size="30">
</form>
Basically, you can do string.capitalize()
and it’ll capitalize every 1st letter of each word.
Source: http://www.mediacollege.com/internet/javascript/text/case-capitalize.html
Pugazh
9,4435 gold badges33 silver badges54 bronze badges
answered Feb 25, 2010 at 9:18
Buhake SindiBuhake Sindi
87.3k28 gold badges167 silver badges226 bronze badges
4
If you’re using lodash in your JavaScript application, You can use _.capitalize:
console.log( _.capitalize('ÿöur striñg') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
vsync
115k56 gold badges298 silver badges391 bronze badges
answered Mar 20, 2018 at 12:45
vicke4vicke4
2,2651 gold badge19 silver badges20 bronze badges
This should cover most basic use cases.
const capitalize = (str) => {
if (typeof str !== 'string') {
throw Error('Feed me string')
} else if (!str) {
return ''
} else {
return str
.split(' ')
.map(s => {
if (s.length == 1 ) {
return s.toUpperCase()
} else {
const firstLetter = s.split('')[0].toUpperCase()
const restOfStr = s.substr(1, s.length).toLowerCase()
return firstLetter + restOfStr
}
})
.join(' ')
}
}
capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week
Edit: Improved readability of mapping.
answered Aug 30, 2018 at 2:06
DropsDrops
2,68018 silver badges16 bronze badges
8
This solution dose not use regex, supports accented characters and also supported by almost every browser.
function capitalizeIt(str) {
if (str && typeof(str) === "string") {
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
if (str[i]) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
}
return str.join(" ");
} else {
return str;
}
}
Usage:
console.log(capitalizeIt(‘çao 2nd inside Javascript programme’));
Output:
Çao 2nd Inside Javascript Programme
Eric Aya
69.2k35 gold badges180 silver badges251 bronze badges
answered Feb 12, 2019 at 10:17
1
http://www.mediacollege.com/internet/javascript/text/case-capitalize.html is one of many answers out there.
Google can be all you need for such problems.
A naïve approach would be to split the string by whitespace, capitalize the first letter of each element of the resulting array and join it back together. This leaves existing capitalization alone (e.g. HTML stays HTML and doesn’t become something silly like Html). If you don’t want that affect, turn the entire string into lowercase before splitting it up.
answered Feb 25, 2010 at 9:14
Alan PlumAlan Plum
10.8k4 gold badges39 silver badges57 bronze badges
This code capitalize words after dot:
function capitalizeAfterPeriod(input) {
var text = '';
var str = $(input).val();
text = convert(str.toLowerCase().split('. ')).join('. ');
var textoFormatado = convert(text.split('.')).join('.');
$(input).val(textoFormatado);
}
function convert(str) {
for(var i = 0; i < str.length; i++){
str[i] = str[i].split('');
if (str[i][0] !== undefined) {
str[i][0] = str[i][0].toUpperCase();
}
str[i] = str[i].join('');
}
return str;
}
answered Aug 23, 2016 at 15:02
I like to go with easy process. First Change string into Array for easy iterating, then using map function change each word as you want it to be.
function capitalizeCase(str) {
var arr = str.split(' ');
var t;
var newt;
var newarr = arr.map(function(d){
t = d.split('');
newt = t.map(function(d, i){
if(i === 0) {
return d.toUpperCase();
}
return d.toLowerCase();
});
return newt.join('');
});
var s = newarr.join(' ');
return s;
}
answered May 9, 2017 at 8:39
Jquery or Javascipt doesn’t provide a built-in method to achieve this.
CSS test transform (text-transform:capitalize;) doesn’t really capitalize the string’s data but shows a capitalized rendering on the screen.
If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>
var capitalizeString = function (word) {
word = word.toLowerCase();
if (word.indexOf(" ") != -1) { // passed param contains 1 + words
word = word.replace(/s/g, "--");
var result = $.camelCase("-" + word);
return result.replace(/-/g, " ");
} else {
return $.camelCase("-" + word);
}
}
answered Jul 24, 2017 at 17:39
siwalikmsiwalikm
1,7621 gold badge16 silver badges20 bronze badges
Use This:
String.prototype.toTitleCase = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
let str = 'text';
document.querySelector('#demo').innerText = str.toTitleCase();
<div class = "app">
<p id = "demo"></p>
</div>
answered Apr 10, 2018 at 9:07
SanjaySanjay
5302 gold badges12 silver badges28 bronze badges
You can use the following to capitalize words in a string:
function capitalizeAll(str){
var partes = str.split(' ');
var nuevoStr = "";
for(i=0; i<partes.length; i++){
nuevoStr += " "+partes[i].toLowerCase().replace(/bw/g, l => l.toUpperCase()).trim();
}
return nuevoStr;
}
Grant Miller
26.9k16 gold badges145 silver badges160 bronze badges
answered Sep 24, 2018 at 20:13
0
There’s also locutus: https://locutus.io/php/strings/ucwords/ which defines it this way:
function ucwords(str) {
// discuss at: http://locutus.io/php/ucwords/
// original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// improved by: Waldo Malqui Silva (http://waldo.malqui.info)
// improved by: Robin
// improved by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
// input by: James (http://www.james-bell.co.uk/)
// example 1: ucwords('kevin van zonneveld')
// returns 1: 'Kevin Van Zonneveld'
// example 2: ucwords('HELLO WORLD')
// returns 2: 'HELLO WORLD'
// example 3: ucwords('у мэри был маленький ягненок и она его очень любила')
// returns 3: 'У Мэри Был Маленький Ягненок И Она Его Очень Любила'
// example 4: ucwords('τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός')
// returns 4: 'Τάχιστη Αλώπηξ Βαφής Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνός'
return (str + '').replace(/^(.)|s+(.)/g, function ($1) {
return $1.toUpperCase();
});
};
answered Apr 23, 2020 at 10:30
geoidesicgeoidesic
4,5493 gold badges36 silver badges55 bronze badges
I would use regex for this purpose:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/wS*/g, (w) => (w.replace(/^w/, (c) => c.toUpperCase())));
answered Jun 24, 2020 at 12:55
Convert text to make each word start with an initial uppercase or capital letter. For example “See me run” becomes “See Me Run” instead. One rule of standard English is to capitalize a proper noun that is a specific person (such as John Smith), place (such as Paris), or thing (such as the Eiffel Tower).
Another rule is to capitalize the first word of a sentence or quote such as he said, “Yes, I will.” The names of days and months such as Tuesday and January are also capitalized as are holidays such as Halloween and Memorial Day. Capitalize a person’s title when used with their name such as President Smith will speak, and when a president speaks we always attend.
Capitalize a direction when it refers to an area such as when you come from the West, but do not capitalize if you refer to a direction such as I go north on Main Street every day. Capitalize words such as Main Street when they refer to a specific location not just a street in the city. Concerning capital letters in other languages, these vary greatly from language to language with German a particular example of rules that depart from English standard usage.
Some writing systems make no distinction between uppercase and lowercase.
In this article we will discuss 5 different ways to convert first letter of each word in a string to uppercase. We will also discuss what are the limitations of each approach and which one is best for us.
Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.
Let’s use this to capitalize the first letter of each word in a string,
sample_text = "this is a sample string" # Capitalize the first letter of each word i.e. # Convert the first letter of each word to Upper case and all other to lower case result = sample_text.title() print(result)
Output:
Advertisements
This Is A Sample String
It worked fine with this solution, but there is a caveat. The title() function not only capitalize the first letter of each word in a string but also makes all remaining characters of each word to upper case. For example,
sample_text = "33a. it's GONE too far" # Capitalize the first letter of each word result = sample_text.title() print(result)
Output:
33A. It'S Gone Too Far
There are 3 unexpected behaviors in above example,
- In this example it converted “GONE” to “Gone”, because for each word in string it makes only first character as upper case and all remaining characters as lower case.
- It converted “it’s” to “It’S” , because it considered “it’s” as two separate words.
- It converted “33a” to “33A” , because it considered “a” as the first letter of word ’33a’.
So, title() function is not the best solution for capitalizing the first letter of each word in a string. Let’s discuss an another solution,
Use capitalize() to capitalize the first letter of each word in a string
Python’s Str class provides a function capitalize(), it converts the first character of string to upper case. Where as it is already in upper case then it does nothing.
We can use this capitalize() to capitalize the first letter of each word in a string. For that, we need to split our string to a list of words and then on each word in the list we need to call the capitalize() function. Then we need to join all the capitalized words to form a big string.
Let’s understand this with an example,
def capitalize_each_word(original_str): result = "" # Split the string and get all words in a list list_of_words = original_str.split() # Iterate over all elements in list for elem in list_of_words: # capitalize first letter of each word and add to a string if len(result) > 0: result = result + " " + elem.strip().capitalize() else: result = elem.capitalize() # If result is still empty then return original string else returned capitalized. if not result: return original_str else: return result sample_text = "33a. it's GONE too far" result = capitalize_each_word(sample_text) print(result)
Output:
33a. It's Gone Too Far
It converted the first letter of each word in string to upper case.
Instead of writing the big function, we can achieve same using generator expressions i.e.
sample_text = "33a. it's GONE too far" result = ' '.join(elem.capitalize() for elem in sample_text.split()) print(result)
Output:
33a. It's Gone Too Far
Here we split the string to words and iterated our each word in string using generator expression. While iterating, we called the capitalized() function on each word, to convert the first letter to uppercase and the joined that word to a string using ‘ ‘ as delimiter.
It served the purpose, but there can be one issue in this approach i.e. if words in original string are separated by more than one white spaces or tabs etc. Then this approach can cause error, because we are joining all capitalized words using same delimiter i.e. a single white space. Checkout this example,
sample_text = "this is a sample string" result = ' '.join(elem.capitalize() for elem in sample_text.split()) print(result)
Output:
This Is A Sample String
Here original string had multiple spaces between words, but in our final string all capitalized words are separated by a single white space. For some this might not be the correct behavior. So, to rectify this problem checkout our next approach.
Using string.capwords() to capitalize the first letter of each word in a string
Python’s string module provides a function capwords() to convert the first letter to uppercase and all other remaining letters to lower case.
It basically splits the string to words and after capitalizing each word, joins them back using a given seperator. Checkout this example,
import string sample_text = "it's gone tOO far" result = string.capwords(sample_text) print(result)
Output:
It's Gone Too Far
Problem with is solution is that it not only converts the first letter of word to uppercase but also makes the remaining letters of word to lower case. For some, this might not be the correct solution.
So, let’s discuss our final and best solution that does what’s only expected from it.
Using Regex to capitalize the first letter of each word in a string
Using regex, we will look for the starting character of each word and the convert to uppercase. For example,
import re def convert_to_uupercase(m): """Convert the second group to uppercase and join both group 1 & group 2""" return m.group(1) + m.group(2).upper() sample_text = "it's gone tOO far" result = re.sub("(^|s)(S)", convert_to_uupercase, sample_text) print(result)
Output:
It's Gone TOO Far
It capitalized only first character of each word in string and do not modifies the whitespaces between words.
How did it worked ?
We created use a pattern “(^|s)(S)”. It looks for string patterns that starts with zero or more whitespaces and then has a non whitespace character after that. Then for each matching instance, it grouped both initial whitespaces and the first character as separate groups. Using regex.sub() function, we passed each matching instance of the pattern to a function convert_to_uppercase(), which converts the second group i.e. first letter of word to upper case and then joins it with the first group(zero or more white spaces).
For string,
sample_text = "it's gone tOO far"
The function convert_to_uupercase() was called 4 times by regex.sub() and in each call group 1 & 2 of match object were,
'' and 'i' ' ' and 'g' ' ' and 't' ' ' and 'f'
Inside convert_to_uupercase(), it converted the second group i.e. first character of each word to uppercase.
So, this is how we can capitalize the first letter of each word in a string using regex and without affecting any other character of the string.
The complete example is as follows,
import string import re def capitalize_each_word(original_str): result = "" # Split the string and get all words in a list list_of_words = original_str.split() # Iterate over all elements in list for elem in list_of_words: # capitalize first letter of each word and add to a string if len(result) > 0: result = result + " " + elem.strip().capitalize() else: result = elem.capitalize() # If result is still empty then return original string else returned capitalized. if not result: return original_str else: return result def main(): print('*** capitalize the first letter of each word in a string ***') print('*** Use title() to capitalize the first letter of each word in a string ***') print('Example 1:') sample_text = "this is a sample string" # Capitalize the first letter of each word i.e. # Convert the first letter of each word to Upper case and all other to lower case result = sample_text.title() print(result) print('Example 2:') sample_text = "33a. it's GONE too far" # Capitalize the first letter of each word result = sample_text.title() print(result) print('*** Use capitalize() to capitalize the first letter of each word in a string ***') sample_text = "33a. it's GONE too far" result = capitalize_each_word(sample_text) print(result) print('Using capitalize() and generator expression') result = ' '.join(elem.capitalize() for elem in sample_text.split()) print(result) print('Example 2:') sample_text = "this is a sample string" result = ' '.join(elem.capitalize() for elem in sample_text.split()) print(result) print('*** Using string.capwords() to capitalize the first letter of each word in a string ***') sample_text = "it's gone tOO far" result = string.capwords(sample_text) print(result) print('*** Using Regex to capitalize the first letter of each word in a string ***') sample_text = "it's gone tOO far" result = re.sub("(^|s)(S)", convert_to_uupercase, sample_text) print(result) def convert_to_uupercase(m): """Convert the second group to uppercase and join both group 1 & group 2""" return m.group(1) + m.group(2).upper() if __name__ == '__main__': main()
Output:
*** capitalize the first letter of each word in a string *** *** Use title() to capitalize the first letter of each word in a string *** Example 1: This Is A Sample String Example 2: 33A. It'S Gone Too Far *** Use capitalize() to capitalize the first letter of each word in a string *** 33a. It's Gone Too Far Using capitalize() and generator expression 33a. It's Gone Too Far Example 2: This Is A Sample String *** Using string.capwords() to capitalize the first letter of each word in a string *** It's Gone Too Far *** Using Regex to capitalize the first letter of each word in a string *** It's Gone TOO Far
If you want to quickly capitalize all letters in a cell, or range of cells in Google Sheets, this can be done by using the UPPER function. The UPPER function is very easy to use, since all you need to do to use it, is to designate the cell that contains the text which you would like to capitalize.
To capitalize all letters in Google Sheets, do the following:
- Type «=UPPER(» into a spreadsheet cell, to begin your function
- Type «A2» (or any cell reference that you want) to refer to the cell that contains the text that you want to capitalize
- Type «)» to include an ending parenthesis with your function
- Then press enter, and your text will now be capitalized
- (Optional) Click and drag the fill handle to copy the formula down, or use ARRAYFORMULA to extend your formula
After following the instructions above, your formula should look like the formula shown below.
Click here to get your Google Sheets cheat sheet
UPPER formula examples:
Capitalize all letters
- =UPPER(A2)
Capitalize all letters in a column
- =ARRAYFORMULA(UPPER(A2:A))
Get your FREE Google Sheets formula cheat sheet
This article focuses specifically on the UPPER function, which is one of the three «change case» formulas in Google Sheets. Where the UPPER function will capitalize every letter, the LOWER function will make every letter lowercase, and the PROPER function will capitalize the first letter of every word.
To learn more about all three of these case changing formulas, check out the article below. But in this article we will stick to using UPPER.
«How to change text case in Google Sheets with UPPER/ LOWER/ PROPER»
The Google Sheets UPPER function will automatically capitalize every single letter in the text that it refers to.
The UPPER function is a very simple function that only requires you to assign a cell reference to specify the location of the text that you want to capitalize.
Google Sheets description for the UPPER function:
Syntax:
UPPER(text)Formula summary: “Converts a specified string to uppercase”
In the examples below, I will show you several ways to use the UPPER function in Google Sheets, to capitalize a string of text, or in other words how to capitalize the text that is contained in a cell.
Then later I will also show you how to capitalize an entire column with the UPPER function.
Capitalize all letters in a Google spreadsheet
Let’s begin with a simple example, where we will capitalize the text that is entered into a single spreadsheet cell in Google Sheets.
Let’s say that you had previously written a message for others to see in a spreadsheet, and that you want to change it to all capital letters so that it will stand out and so that others will know that it is important.
Instead of changing each letter to uppercase manually, you can use the UPPER function to automatically change every letter of the sentence to uppercase.
The task: Capitalize every letter in an entire sentence
The logic: Capitalize all letters in cell A1, by using the UPPER function
The formula: The formula below, is entered in the blue cell (B1), for this example
=UPPER(A1)
You can see that in the example above, every letter of the sentence that was originally lowercase, has now been capitalized.
Capitalize text in strings that have both text and numbers
The Google Sheets UPPER function can also be used to capitalize letters in situations where there is more than just text in the spreadsheet cells.
When there is punctuation or numbers mixed in with the text that the UPPER function refers to, the formula will still function properly, and will capitalize all letters while ignoring non-text characters.
For example, let’s say that you have a list of product codes that contain both letters and numbers that were given to you at your job… and that they were given to you with the letters in lowercase format even though they must be entered into the system with all uppercase letters.
Instead of asking an employee to re-type the product codes in the correct format which would be time-consuming, you can simply use the UPPER function to automatically capitalize every letter in the data that was given to you.
In the example below, this is exactly the task that we will perform.
But an added component to this example, is that the formula has been copied into the cells below it, so that each product code is capitalized with a new formula in each row.
The task: Change the letters in the product codes to uppercase letters
The logic: Use the UPPER function to capitalize all letters that are found in the range A2:A15
The formula: The formula below, is initially entered in the cell C2, and then copied into the cells below it, for this example
=UPPER(A2)
Notice that in the example above, all of the letters in the product codes have now been capitalized, which makes them easy to read, and makes the codes look very uniform and clean as the capital letters are the same height of the numbers.
Using the UPPER function to capitalize text in a column
In the last example, we capitalized the data in a column by copying a formula into every cell within a range. But you may sometimes want to capitalize a whole column, by using a single formula that applies to multiple cells.
You can do this by using the ARRAYFORMULA function to extend the UPPER function, so that a single formula applies to a range of cells.
To capitalize every letter of the text that is in an entire column in a Google spreadsheet, do the following:
- Enter an UPPER formula that applies to a single cell at the top of the list that you want to capitalize, like this =UPPER(A2)
- Modify the cell reference so that it represents a range of cells, like this =UPPER(A2:A) Note that this formula will not apply to a range yet, because you must use ARRAYFORMULA
- Wrap your formula in the «ARRAYFORMULA» function, like this =ARRAYFORMULA(UPPER(A2:A))
Below, is an example of using ARRAYFORMULA with UPPER, to capitalize multiple cells by using a single formula.
In this scenario, let’s say that we have a list of addresses in a spreadsheet, and that we need to make it so that the addresses appear in all capital letters. This time, we let’s say that we don’t want to have to copy formulas down the column in order to capitalize every address.
This is where we will use the ARRAYFORMULA function to capitalize the text in a whole column.
The task: Capitalize all of the addresses
The logic: Combine the UPPER function with the ARRAYFORMULA function to change all of the letters in column A to uppercase
The formula: The formula below, is entered in the blue cell (C2), for this example
=ARRAYFORMULA(UPPER(A2:A))
You can see that in the example above, every address in the list has been completely capitalized, with the use of a single formula.
Pop Quiz: Test your knowledge
Answer the questions below about the UPPER function, to refine your knowledge! Scroll to the very bottom to find the answers to the quiz.
Classroom downloads:
UPPER function cheat sheet (PDF)
Click here to get your Google Sheets cheat sheet
Click the green «Print» button below to print this entire article.
Question #1
Which of the following is a correct formula that will capitalize ALL letters?
- =UPPERCASE(A1)
- =UPPER(A1)
- =PROPER(A1)
Question #2
Which of the following options represents how the this phrase «I like Google Sheets» would appear after the UPPER function was applied to it?
- I LIKE Google Sheets
- I Like Google Sheets
- I LIKE GOOGLE SHEETS
Question #3
True or False: If you referred to a cell that contained this string «123abc?» with the UPPER function, it would cause a formula error.
- True
- False
Answers to the questions above:
Question 1: 2
Question 2: 3
Question 3: 2
In this article, you are going to learn how to capitalize the first letter of any word in JavaScript. After that, you are going to capitalize the first letter of all words from a sentence.
The beautiful thing about programming is that there is no one universal solution to solve a problem. Therefore, in this article you are going to see multiple ways of solving the same problem.
First of all, let’s start with capitalizing the first letter of a single word. After you learn how to do this, we’ll proceed to the next level – doing it on every word from a sentence. Here is an example:
const publication = "freeCodeCamp";
In JavaScript, we start counting from 0. For instance, if we have an array, the first position is 0, not 1.
Also, we can access each letter from a String in the same way that we access an element from an array. For instance, the first letter from the word «freeCodeCamp» is at position 0.
This means that we can get the letter f from freeCodeCamp by doing publication[0]
.
In the same way, you can access other letters from the word. You can replace «0» with any number, as long as you do not exceed the word length. By exceeding the word length, I mean trying to do something like publication[25
, which throws an error because there are only twelve letters in the word «freeCodeCamp».
How to capitalize the first letter
Now that we know how to access a letter from a word, let’s capitalize it.
In JavaScript, we have a method called toUpperCase()
, which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase.
For instance:
const publication = "freeCodeCamp";
publication[0].toUpperCase();
Running the above code, you are going to get a capital F instead of f. To get the whole word back, we can do this:
const publication = "freeCodeCamp";
publication[0].toUpperCase() + publication.substring(1);
Now it concatenates «F» with «reeCodeCamp», which means we get back the word «FreeCodeCamp». That is all!
Let’s recap
To be sure things are clear, let’s recap what we’ve learnt so far:
- In JavaScript, counting starts from 0.
- We can access a letter from a string in the same way we access an element from an array — e.g.
string[index]
. - Do not use an index that exceeds the string length (use the length method —
string.length
— to find the range you can use). - Use the built-in method
toUpperCase()
on the letter you want to transform to uppercase.
Capitalize the first letter of each word from a string
The next step is to take a sentence and capitalize every word from that sentence. Let’s take the following sentence:
const mySentence = "freeCodeCamp is an awesome resource";
Split it into words
We have to capitalize the first letter from each word from the sentence freeCodeCamp is an awesome resource
.
The first step we take is to split the sentence into an array of words. Why? So we can manipulate each word individually. We can do that as follows:
const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");
Iterate over each word
After we run the above code, the variable words
is assigned an array with each word from the sentence. The array is as follows ["freeCodeCamp", "is", "an", "awesome", "resource"]
.
const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
Now the next step is to loop over the array of words and capitalize the first letter of each word.
In the above code, every word is taken separately. Then it capitalizes the first letter, and in the end, it concatenates the capitalized first letter with the rest of the string.
Join the words
What is the above code doing? It iterates over each word, and it replaces it with the uppercase of the first letter + the rest of the string.
If we take «freeCodeCamp» as an example, it looks like this freeCodeCamp = F + reeCodeCamp
.
After it iterates over all the words, the words
array is ["FreeCodeCamp", "Is", "An", "Awesome", "Resource"]
. However, we have an array, not a string, which is not what we want.
The last step is to join all the words to form a sentence. So, how do we do that?
In JavaScript, we have a method called join
, which we can use to return an array as a string. The method takes a separator as an argument. That is, we specify what to add between words, for example a space.
const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
words.join(" ");
In the above code snippet, we can see the join method in action. We call it on the words
array, and we specify the separator, which in our case is a space.
Therefore, ["FreeCodeCamp", "Is", "An", "Awesome", "Resource"]
becomes FreeCodeCamp Is An Awesome Resource
.
Other methods
In programming, usually, there are multiple ways of solving the same problem. So let’s see another approach.
const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");
words.map((word) => {
return word[0].toUpperCase() + word.substring(1);
}).join(" ");
What is the difference between the above solution and the initial solution? The two solutions are very similar, the difference being that in the second solution we are using the map
function, whereas in the first solution we used a for loop
.
Let’s go even further, and try to do a one-liner. Be aware! One line solutions might look cool, but in the real world they are rarely used because it is challenging to understand them. Code readability always comes first.
const mySentence = "freeCodeCamp is an awesome resource";
const finalSentence = mySentence.replace(/(^w{1})|(s+w{1})/g, letter => letter.toUpperCase());
The above code uses RegEx to transform the letters. The RegEx might look confusing, so let me explain what happens:
^
matches the beginning of the string.w
matches any word character.{1}
takes only the first character.- Thus,
^w{1}
matches the first letter of the word. |
works like the booleanOR
. It matches the expression after and before the|
.s+
matches any amount of whitespace between the words (for example spaces, tabs, or line breaks).
Thus, with one line, we accomplished the same thing we accomplished in the above solutions. If you want to play around with the RegEx and to learn more, you can use this website.
Conclusion
Congratulations, you learnt a new thing today! To recap, in this article, you learnt how to:
- access the characters from a string
- capitalize the first letter of a word
- split a string in an array of words
- join back the words from an array to form a string
- use RegEx to accomplish the same task
Thanks for reading! If you want to keep in touch, let’s connect on Twitter @catalinmpit. I also publish articles regularly on my blog catalins.tech if you want to read more content from me.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Schism’s answer touches on the important points: use snake_case, implicit return, and use map
rather than modifying the string instances in-place with a bang-method (!
).
However, if the string contains many kinds of whitespace — linebreaks, tabs; not just " "
— it may not work as intended.
You could consider using gsub
in order to maintain any and all original whitespace:
def capitalize_words(string)
string.gsub(/S+/, &:capitalize)
end
This will capitalize words separated by any kind of whitespace, and preserve that whitespace in the resulting string.
The regular expression will match 1 or more consecutive non-whitespace characters (i.e. it’ll match individual words), which are then passed to an implicit block that calls capitalize
on the word, replacing it in the string.
E.g.
input = "here's a STRING withnta newline aNd a tab character"
puts capitalize_words(input)
will print
Here's A String With A Newline And A Tab Character
(StackExchange’s system seems to replace the tab character with 4 spaces, but run the code yourself, and it’ll remain a t
)
As for monkey patching the String
class… up to you. I’d consider it for something like this, but I wouldn’t do it immediately. The functionality is generic enough that it’d make sense as an addition to String
, but, IMO, the real question is whether its usage is wide-spread enough. If the functionality is only used in a few places, then don’t start messing with basic classes.