The word “with” is fairly common in titles, so it’s important to know whether it should be capitalized. Unfortunately, the rules are not straightforward. First, the answer depends on which style you are using. It also depends on whether the word is part of a phrasal verb.
Capitalizing “With” in Chicago and MLA Styles
According to the Chicago Manual of Style and MLA style guide the word “with” should always be lowercase in a title unless it is the first or last word in a sentence. This is because “with” is a preposition with four letters which means it should be lowercase.
Examples:
- I Am with You (Chicago Style)
- Come with Me (MLA Style)
Capitalizing Phrasal Verbs
Phrasal verbs consist of a verb and another element, typically either an adverb or a preposition. Since “with” is a preposition, when paired with a verb, the phrase becomes a phrasal verb and phrasal verbs are capitalized because verbs are capitalized in MLA and Chicago.
For example, the phrase “Come Play With Me Now” has the “with” capitalized because it is part of the phrasal verb “play with”.
Capitalizing “With” in APA and AP Styles
However, in APA and AP Stylebook, the word “with” is capitalized because all words longer than four words are capitalized.
Examples:
- I Am With You (APA Style)
- Come With Me (AP Style)
The same rules as “with” apply for the word “within”. You should capitalize it in APA and AP styles, but lowercase it in Chicago and MLA styles unless the word is being used as an adverb or is used in a phrasal verb.
This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.
In this algorithm, we want to change a string of text so that it always has a capital letter at the start of every word.
In this article, I’m going to explain three approaches. First with a FOR loop, second using the map() method, and third using the replace() method.
Algorithm Challenge
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
For the purpose of this exercise, you should also capitalize connecting words like “the” and “of”.
Provided test cases
- titleCase(“I’m a little tea pot”) should return a string.
- titleCase(“I’m a little tea pot”) should return “I’m A Little Tea Pot”.
- titleCase(“sHoRt AnD sToUt”) should return “Short And Stout”.
- titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”) should return “Here Is My Handle Here Is My Spout”.
1. Title Case a Sentence With a FOR Loop
For this solution, we will use the String.prototype.toLowerCase() method, the String.prototype.split() method, the String.prototype.charAt() method, the String.prototype.slice() method and the Array.prototype.join() method.
- The toLowerCase() method returns the calling string value converted to lowercase
- The split() method splits a String object into an array of strings by separating the string into substrings.
- The charAt() method returns the specified character from a string.
- The slice() method extracts a section of a string and returns a new string.
- The join() method joins all elements of an array into a string.
We will need to add an empty space between the parenthesis of the split()method,
var strSplit = "I'm a little tea pot".split(' ');
which will output an array of separated words:
var strSplit = ["I'm", "a", "little", "tea", "pot"];
If you don’t add the space in the parenthesis, you will have this output:
var strSplit = ["I", "'", "m", " ", "a", " ", "l", "i", "t", "t", "l", "e", " ", "t", "e", "a", " ", "p", "o", "t"];
We will concatenate
str[i].charAt(0).toUpperCase()
— which will uppercase the index 0 character of the current string in the FOR loop —
and
str[i].slice(1)
— which will extract from index 1 to the end of the string.
We will set the whole string to lower case for normalization purposes.
function titleCase(str) {
// Step 1. Lowercase the string
str = str.toLowerCase();
// str = "I'm a little tea pot".toLowerCase();
// str = "i'm a little tea pot";
// Step 2. Split the string into an array of strings
str = str.split(' ');
// str = "i'm a little tea pot".split(' ');
// str = ["i'm", "a", "little", "tea", "pot"];
// Step 3. Create the FOR loop
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
/* Here str.length = 5
1st iteration: str[0] = str[0].charAt(0).toUpperCase() + str[0].slice(1);
str[0] = "i'm".charAt(0).toUpperCase() + "i'm".slice(1);
str[0] = "I" + "'m";
str[0] = "I'm";
2nd iteration: str[1] = str[1].charAt(0).toUpperCase() + str[1].slice(1);
str[1] = "a".charAt(0).toUpperCase() + "a".slice(1);
str[1] = "A" + "";
str[1] = "A";
3rd iteration: str[2] = str[2].charAt(0).toUpperCase() + str[2].slice(1);
str[2] = "little".charAt(0).toUpperCase() + "little".slice(1);
str[2] = "L" + "ittle";
str[2] = "Little";
4th iteration: str[3] = str[3].charAt(0).toUpperCase() + str[3].slice(1);
str[3] = "tea".charAt(0).toUpperCase() + "tea".slice(1);
str[3] = "T" + "ea";
str[3] = "Tea";
5th iteration: str[4] = str[4].charAt(0).toUpperCase() + str[4].slice(1);
str[4] = "pot".charAt(0).toUpperCase() + "pot".slice(1);
str[4] = "P" + "ot";
str[4] = "Pot";
End of the FOR Loop*/
}
// Step 4. Return the output
return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}
titleCase("I'm a little tea pot");
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(' ');
}
titleCase("I'm a little tea pot");
2. Title Case a Sentence With the map() Method
For this solution, we will use the Array.prototype.map() method.
- The map() method creates a new array with the results of calling a provided function on every element in this array. Using map will call a provided callback function once for each element in an array, in order, and constructs a new array from the results.
We will lowercase and split the string as seen in the previous example before applying the map() method.
Instead of using a FOR loop, we will apply the map() method as the condition on the same concatenation from the previous example.
(word.charAt(0).toUpperCase() + word.slice(1));
function titleCase(str) {
// Step 1. Lowercase the string
str = str.toLowerCase() // str = "i'm a little tea pot";
// Step 2. Split the string into an array of strings
.split(' ') // str = ["i'm", "a", "little", "tea", "pot"];
// Step 3. Map over the array
.map(function(word) {
return (word.charAt(0).toUpperCase() + word.slice(1));
/* Map process
1st word: "i'm" => (word.charAt(0).toUpperCase() + word.slice(1));
"i'm".charAt(0).toUpperCase() + "i'm".slice(1);
"I" + "'m";
return "I'm";
2nd word: "a" => (word.charAt(0).toUpperCase() + word.slice(1));
"a".charAt(0).toUpperCase() + "".slice(1);
"A" + "";
return "A";
3rd word: "little" => (word.charAt(0).toUpperCase() + word.slice(1));
"little".charAt(0).toUpperCase() + "little".slice(1);
"L" + "ittle";
return "Little";
4th word: "tea" => (word.charAt(0).toUpperCase() + word.slice(1));
"tea".charAt(0).toUpperCase() + "tea".slice(1);
"T" + "ea";
return "Tea";
5th word: "pot" => (word.charAt(0).toUpperCase() + word.slice(1));
"pot".charAt(0).toUpperCase() + "pot".slice(1);
"P" + "ot";
return "Pot";
End of the map() method */
});
// Step 4. Return the output
return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}
titleCase("I'm a little tea pot");
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return (word.charAt(0).toUpperCase() + word.slice(1));
}).join(' ');
}
titleCase("I'm a little tea pot");
3. Title Case a Sentence With the map() and the replace() Methods
For this solution, we will keep using the Array.prototype.map() method and add the String.prototype.replace() method.
- The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
In our case, the pattern for the replace() method will be a String to be replaced by a new replacement and will be treated as a verbatim string. We can also use a regular expression as the pattern to solve this algorithm.
We will lowercase and split the string as seen in the first example before applying the map() method.
function titleCase(str) {
// Step 1. Lowercase the string
str = str.toLowerCase() // str = "i'm a little tea pot";
// Step 2. Split the string into an array of strings
.split(' ') // str = ["i'm", "a", "little", "tea", "pot"];
// Step 3. Map over the array
.map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
/* Map process
1st word: "i'm" => word.replace(word[0], word[0].toUpperCase());
"i'm".replace("i", "I");
return word => "I'm"
2nd word: "a" => word.replace(word[0], word[0].toUpperCase());
"a".replace("a", "A");
return word => "A"
3rd word: "little" => word.replace(word[0], word[0].toUpperCase());
"little".replace("l", "L");
return word => "Little"
4th word: "tea" => word.replace(word[0], word[0].toUpperCase());
"tea".replace("t", "T");
return word => "Tea"
5th word: "pot" => word.replace(word[0], word[0].toUpperCase());
"pot".replace("p", "P");
return word => "Pot"
End of the map() method */
});
// Step 4. Return the output
return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}
titleCase("I'm a little tea pot");
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.
Three ways to repeat a string in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…
Two ways to confirm the ending of a String in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.
Three Ways to Reverse a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”
Three Ways to Factorialize a Number in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”
Two Ways to Check for Palindromes in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.
Three Ways to Find the Longest Word in a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.
Three ways you can find the largest number in an array using JavaScript
In this article, I’m going to explain how to solve Free Code Camp’s “Return Largest Numbers in Arrays” challenge. This…
If you have your own solution or any suggestions, share them below in the comments.
Or you can follow me on Medium, Twitter, Github and LinkedIn.
#StayCurious, #KeepOnHacking & #MakeItHappen!
Resources
- toLowerCase() method — MDN
- toUpperCase() method — MDN
- charAt() method — MDN
- slice() method — MDN
- split() method — MDN
- join() method — MDN
- for — MDN
- map() method — MDN
- replace() method — MDN
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Asked
14 years, 6 months ago
Viewed
650k times
Is there a simple way to convert a string to Title Case? E.g. john smith
becomes John Smith
. I’m not looking for something complicated like John Resig’s solution, just (hopefully) some kind of one- or two-liner.
Penny Liu
14.5k5 gold badges77 silver badges93 bronze badges
asked Oct 13, 2008 at 8:05
5
Try this:
function toTitleCase(str) {
return str.replace(
/wS*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>
meyi
7,2841 gold badge16 silver badges28 bronze badges
answered Oct 13, 2008 at 8:18
Greg DeanGreg Dean
28.9k14 gold badges67 silver badges77 bronze badges
20
If a CSS solution meets your needs, you can apply the text-transform CSS style to your controls:
text-transform: capitalize;
Just be aware that this will transform:
hello world
to Hello World
HELLO WORLD
to HELLO WORLD
(no change)
emily-jane o'brien
to Emily-jane O'brien
(incorrect)
Maria von Trapp
to Maria Von Trapp
(incorrect)
Michael
8,1716 gold badges62 silver badges88 bronze badges
answered Jun 16, 2010 at 14:58
Talha AshfaqueTalha Ashfaque
3,5001 gold badge14 silver badges7 bronze badges
13
A slightly more elegant way, adapting Greg Dean’s function:
String.prototype.toProperCase = function () {
return this.replace(/wS*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Call it like:
"pascal".toProperCase();
answered Apr 7, 2011 at 0:14
TuanTuan
5,3531 gold badge21 silver badges17 bronze badges
8
Here’s my version, IMO it’s easy to understand and elegant too.
const str = "foo bar baz";
const newStr = str.split(' ')
.map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
.join(' ');
console.log(newStr);
xinthose
2,9973 gold badges41 silver badges58 bronze badges
answered Mar 5, 2014 at 9:07
a8ma8m
9,3044 gold badges36 silver badges40 bronze badges
9
Here’s my function that converts to title case but also preserves defined acronyms as uppercase and minor words as lowercase:
String.prototype.toTitleCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/([^W_]+[^s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\s' + lowers[i] + '\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\b' + uppers[i] + '\b', 'g'),
uppers[i].toUpperCase());
return str;
}
For example:
"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
answered Jun 25, 2011 at 1:04
Geoffrey BoothGeoffrey Booth
7,0905 gold badges36 silver badges41 bronze badges
10
I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call toLowerCase()
on your string first.
function title(str) {
return str.replace(/(^|s)S/g, function(t) { return t.toUpperCase() });
}
You can add this to your string prototype which will allow you to 'my string'.toTitle()
as follows:
String.prototype.toTitle = function() {
return this.replace(/(^|s)S/g, function(t) { return t.toUpperCase() });
}
Example:
answered Oct 26, 2017 at 16:36
Tom KayTom Kay
1,49215 silver badges25 bronze badges
10
You could immediately toLowerCase
the string, and then just toUpperCase
the first letter of each word. Becomes a very simple 1 liner:
function titleCase(str) {
return str.toLowerCase().replace(/bw/g, s => s.toUpperCase());
}
console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));
answered Oct 18, 2016 at 15:09
KevBotKevBot
17.5k5 gold badges53 silver badges68 bronze badges
7
Benchmark
TL;DR
The winner of this benchmark is the plain old for loop:
function titleize(str) {
let upper = true
let newStr = ""
for (let i = 0, l = str.length; i < l; i++) {
// Note that you can also check for all kinds of spaces with
// str[i].match(/s/)
if (str[i] == " ") {
upper = true
newStr += str[i]
continue
}
newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
upper = false
}
return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.
Details
I’ve taken the most popular and distinct answers and made a benchmark with those.
Here’s the result on my MacBook pro:
And for completeness, here are the functions used:
str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";
function regex(str) {
return str.replace(
/wS*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
function split(str) {
return str.
split(' ').
map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).
join(' ');
}
function complete(str) {
var i, j, str, lowers, uppers;
str = str.replace(/([^W_]+[^s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\s' + lowers[i] + '\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\b' + uppers[i] + '\b', 'g'),
uppers[i].toUpperCase());
return str;
}
function firstLetterOnly(str) {
return str.replace(/b(S)/g, function(t) { return t.toUpperCase(); });
}
function forLoop(str) {
let upper = true;
let newStr = "";
for (let i = 0, l = str.length; i < l; i++) {
if (str[i] == " ") {
upper = true;
newStr += " ";
continue;
}
newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();
upper = false;
}
return newStr;
}
Note that i deliberately did not change the prototype since I consider it a really bad practice and I don’t think we should promote such practice in our answers. This is only ok for small codebases when you’re the only one working on it.
If you want to add any other way to do it to this benchmark, please comment a link to the answer !
EDIT 2022 Mac M1: On my new computer, with more recent chrome, split wins. If you really care about performance on a specific machine you should run the benchmark yourself
answered Nov 19, 2020 at 10:56
Ulysse BNUlysse BN
9,7887 gold badges52 silver badges79 bronze badges
4
var result =
'this is very interesting'.replace(/b[a-z]/g, (x) => x.toUpperCase())
console.log(result) // This Is Very Interesting
answered Dec 24, 2013 at 15:17
simosimo
14.9k7 gold badges45 silver badges59 bronze badges
5
Without using regex just for reference:
String.prototype.toProperCase = function() {
var words = this.split(' ');
var results = [];
for (var i = 0; i < words.length; i++) {
var letter = words[i].charAt(0).toUpperCase();
results.push(letter + words[i].slice(1));
}
return results.join(' ');
};
console.log(
'john smith'.toProperCase()
)
adiga
34k9 gold badges58 silver badges82 bronze badges
answered Dec 19, 2011 at 16:25
MikeMike
4373 silver badges6 bronze badges
1
Surprised to see no one mentioned the use of rest parameter. Here is a simple one liner that uses ES6 Rest parameters.
let str="john smith"
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")
console.log(str)
answered May 18, 2020 at 16:53
kapil pandeykapil pandey
1,7731 gold badge13 silver badges26 bronze badges
1
Just in case you are worried about those filler words, you can always just tell the function what not to capitalize.
/**
* @param String str The text to be converted to titleCase.
* @param Array glue the words to leave in lowercase.
*/
var titleCase = function(str, glue){
glue = (glue) ? glue : ['of', 'for', 'and'];
return str.replace(/(w)(w*)/g, function(_, i, r){
var j = i.toUpperCase() + (r != null ? r : "");
return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
});
};
Hope this helps you out.
edit
If you want to handle leading glue words, you can keep track of this w/ one more variable:
var titleCase = function(str, glue){
glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
var first = true;
return str.replace(/(w)(w*)/g, function(_, i, r) {
var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
first = false;
return result;
});
};
answered Nov 13, 2010 at 5:17
fncompfncomp
5,9903 gold badges33 silver badges42 bronze badges
6
If you need a grammatically correct answer:
This answer takes into account prepositions such as «of», «from», ..
The output will generate an editorial style title you would expect to see in a paper.
toTitleCase Function
The function that takes into account grammar rules listed here.
The function also consolidates whitespace and removes special characters (modify regex for your needs)
const toTitleCase = (str) => {
const articles = ['a', 'an', 'the'];
const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
const prepositions = [
'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
];
// The list of spacial characters can be tweaked here
const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\]/gi, ' ').replace(/(ss+)/gi, ' ');
const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
const normalizeStr = (str) => str.toLowerCase().trim();
const shouldCapitalize = (word, fullWordList, posWithinStr) => {
if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
return true;
}
return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
}
str = replaceCharsWithSpace(str);
str = normalizeStr(str);
let words = str.split(' ');
if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
words = words.map(w => capitalizeFirstLetter(w));
}
else {
for (let i = 0; i < words.length; i++) {
words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
}
}
return words.join(' ');
}
Unit Tests to Ensure Correctness
import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';
describe('toTitleCase', () => {
it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
});
it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
});
it('Replace special characters with space', function(){
expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
});
it('Trim whitespace at beginning and end', function(){
expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
});
it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
expect(toTitleCase('the three Musketeers And plus ')).to.equal('The Three Musketeers and Plus');
});
});
Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.
answered Oct 16, 2017 at 16:17
dipole_momentdipole_moment
5,0263 gold badges39 silver badges55 bronze badges
4
If regex used in the above solutions is getting you confused, try this code:
function titleCase(str) {
return str.split(' ').map(function(val){
return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
}).join(' ');
}
answered Feb 28, 2016 at 10:16
6
I made this function which can handle last names (so it’s not title case) such as «McDonald» or «MacDonald» or «O’Toole» or «D’Orazio». It doesn’t however handle German or Dutch names with «van» or «von» which are often in lower-case… I believe «de» is often lower-case too such as «Robert de Niro». These would still have to be addressed.
function toProperCase(s)
{
return s.toLowerCase().replace( /b((m)(a?c))?(w)/g,
function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}
answered Feb 3, 2010 at 22:22
LwangamanLwangaman
1391 silver badge2 bronze badges
3
If you can use third party libraries in your code then lodash has a helper function for us.
https://lodash.com/docs/4.17.3#startCase
_.startCase('foo bar');
// => 'Foo Bar'
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
answered Dec 29, 2016 at 11:27
waqaswaqas
4,3273 gold badges34 silver badges42 bronze badges
ES 6
str.split(' ')
.map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
.join(' ')
else
str.split(' ').map(function (s) {
return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')
Steve Bennett
110k32 gold badges165 silver badges215 bronze badges
answered Oct 27, 2016 at 15:52
jssridharjssridhar
4604 silver badges10 bronze badges
5
First, convert your string
into array by splitting it by spaces:
var words = str.split(' ');
Then use array.map to create a new array containing the capitalized words.
var capitalized = words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});
Then join the new array with spaces:
capitalized.join(" ");
NOTE:
This of course has a drawback. This will only capitalize the first letter of every word. By word, this means that it treats every string separated by spaces as 1 word.
Supposedly you have:
str = "I'm a little/small tea pot";
This will produce
I’m A Little/small Tea Pot
compared to the expected
I’m A Little/Small Tea Pot
In that case, using Regex and .replace will do the trick:
with ES6:
const capitalize = str => str.length
? str[0].toUpperCase() +
str.slice(1).toLowerCase()
: '';
const escape = str => str.replace(/./g, c => `\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );
or without ES6:
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}
function titleCase(str) {
return str.replace(/[^ /-_]+/g, capitalize);
}
console.log(titleCase("I'm a little/small tea pot."));
answered Sep 30, 2017 at 9:28
xGeoxGeo
2,1392 gold badges19 silver badges39 bronze badges
Most of these answers seem to ignore the possibility of using the word boundary metacharacter (b). A shorter version of Greg Dean’s answer utilizing it:
function toTitleCase(str)
{
return str.replace(/bw/g, function (txt) { return txt.toUpperCase(); });
}
Works for hyphenated names like Jim-Bob too.
answered Jul 16, 2014 at 14:59
lewax00lewax00
1881 silver badge8 bronze badges
3
var toMatch = "john w. smith";
var result = toMatch.replace(/(w)(w*)/g, function (_, i, r) {
return i.toUpperCase() + (r != null ? r : "");
}
)
Seems to work…
Tested with the above, «the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog…» and «C:/program files/some vendor/their 2nd application/a file1.txt».
If you want 2Nd instead of 2nd, you can change to /([a-z])(w*)/g
.
The first form can be simplified as:
function toTitleCase(toTransform) {
return toTransform.replace(/b([a-z])/g, function (_, initial) {
return initial.toUpperCase();
});
}
answered Oct 13, 2008 at 8:17
PhiLhoPhiLho
40.3k6 gold badges96 silver badges132 bronze badges
Try this, shortest way:
str.replace(/(^[a-z])|(s+[a-z])/g, txt => txt.toUpperCase());
Mr. Polywhirl
40.4k12 gold badges82 silver badges129 bronze badges
answered Jun 6, 2017 at 9:52
VikramVikram
6141 gold badge6 silver badges18 bronze badges
1
Try this
String.prototype.toProperCase = function(){
return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g,
function($1){
return $1.toUpperCase();
}
);
};
Example
var str = 'john smith';
str.toProperCase();
answered May 16, 2012 at 19:05
Maxi BaezMaxi Baez
5805 silver badges13 bronze badges
0
Use /S+/g
to support diacritics:
function toTitleCase(str) {
return str.replace(/S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}
console.log(toTitleCase("a city named örebro")); // A City Named Örebro
However: «sunshine (yellow)» ⇒ «Sunshine (yellow)»
answered Jun 20, 2016 at 20:31
le_mle_m
19k9 gold badges63 silver badges74 bronze badges
I think the simplest is using css.
function format_str(str) {
str = str.toLowerCase();
return '<span style="text-transform: capitalize">'+ str +'</span>';
}
answered Jul 7, 2017 at 5:01
wondimwondim
69914 silver badges28 bronze badges
3
"john f. kennedy".replace(/bS/g, t => t.toUpperCase())
answered Jun 21, 2019 at 8:30
ProximoProximo
6,08511 gold badges48 silver badges65 bronze badges
3
Here’s a really simple & concise ES6 function to do this:
const titleCase = (str) => {
return str.replace(/wS*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}
export default titleCase;
Works well included in a utilities
folder and used as follows:
import titleCase from './utilities/titleCase.js';
const string = 'my title & string';
console.log(titleCase(string)); //-> 'My Title & String'
answered Nov 19, 2020 at 10:39
Hedley SmithHedley Smith
1,29915 silver badges12 bronze badges
1
Here is my function that is taking care of accented characters (important for french !) and that can switch on/off the handling of lowers exceptions. Hope that helps.
String.prototype.titlecase = function(lang, withLowers = false) {
var i, string, lowers, uppers;
string = this.replace(/([^s:-'])([^s:-']*)/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/Mc(.)/g, function(match, next) {
return 'Mc' + next.toUpperCase();
});
if (withLowers) {
if (lang == 'EN') {
lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
}
else {
lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
}
for (i = 0; i < lowers.length; i++) {
string = string.replace(new RegExp('\s' + lowers[i] + '\s', 'g'), function(txt) {
return txt.toLowerCase();
});
}
}
uppers = ['Id', 'R&d'];
for (i = 0; i < uppers.length; i++) {
string = string.replace(new RegExp('\b' + uppers[i] + '\b', 'g'), uppers[i].toUpperCase());
}
return string;
}
answered Dec 11, 2016 at 16:36
OuatatazOuatataz
1852 silver badges12 bronze badges
here’s another solution using css (and javascript, if the text you want to transform is in uppercase):
html
<span id='text'>JOHN SMITH</span>
js
var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();
css
#text{text-transform:capitalize;}
answered Oct 25, 2018 at 12:12
henriehenrie
1651 silver badge12 bronze badges
jim-bob -> Jim-Bob
jim/bob -> Jim/Bob
jim_bob -> Jim_Bob
isn’t -> Isn’t
école -> École
McDonalds -> McDonalds
function toTitleCase(str) {
return str.replace(/p{L}+('p{L}+)?/gu, function(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1)
})
}
answered Jan 1, 2022 at 3:13
o17t H1H’ S’ko17t H1H’ S’k
2,4635 gold badges31 silver badges51 bronze badges
I’ve tested this solution for Turkish and it works with special characters too.
function toTitleCase(str) {
return str.toLocaleLowerCase().replace(
/(^|Ü|ü|Ş|ş|Ç|ç|İ|ı|Ö|ö|w)S*/g,
(txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),
)
}
console.log(toTitleCase('İSMAİL HAKKI'))
console.log(toTitleCase('ŞAHMARAN BİNBİR GECE MASALLARI'))
console.log(toTitleCase('TEKNOLOJİ ÜRÜNÜ'))
I’ve added «toLocaleLowerCase» at the begining since I’ve all caps data. You can discard it if you don’t need it.
Using locale operations is important for non-english languages.
answered Jan 12, 2022 at 13:10
KeremKerem
1032 silver badges7 bronze badges
4
CodeWars Python Solutions
Title Case
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string — it should behave in the same way even if the case of the minor word string is changed.
Arguments (Haskell)
- First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.
- Second argument: the original string to be converted.
Arguments (Other languages)
- First argument (required): the original string to be converted.
- Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass
undefined
when this argument is unused.
Examples
title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings' title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows' title_case('the quick brown fox') # should return: 'The Quick Brown Fox'
Given Code
def title_case(title, minor_words=''): pass
Solution
def title_case(title, minor_words=''): words = [] for w in title.split(): if w.lower() not in minor_words.lower().split() or len(words) == 0: words.append(w.title()) else: words.append(w.lower()) return " ".join(words)
See on CodeWars.com
From Wikipedia, the free encyclopedia
Title case or headline case is a style of capitalization used for rendering the titles of published works or works of art in English. When using title case, all words are capitalized, except for minor words (typically articles, short prepositions, and some conjunctions) that are not the first or last word of the title. There are different rules for which words are major, hence capitalized.
As an example, a headline might be written like this: «The Quick Brown Fox Jumps over the Lazy Dog».
Rules[edit]
The rules of title case are not universally standardized. The standardization is only at the level of house styles and individual style guides. Most English style guides agree that the first and last words should always be capitalized, whereas articles, short prepositions, and some conjunctions should not be. Other rules about the capitalization vary.[1]
In text processing, title case usually involves the capitalization of all words irrespective of their part of speech. This simplified variant of title case is also known as start case or initial caps.
AP Stylebook[edit]
According to the Associated Press Stylebook (2020 edition, 55th edition), the following rules should be applied:[2]
- Capitalize the principal words.
- Capitalize prepositions and conjunctions of four letters or more.
- Lowercase the articles the, a, and an.
- Capitalize the first and last words (overrides the rules above).
- Capitalize the «to» in infinitives (e.g., I Want To Play Guitar).[3]
Chicago Manual of Style[edit]
According to the Chicago Manual of Style (15th edition), the following rules should be applied:[4]
- Always capitalize «major» words (nouns, pronouns, verbs, adjectives, adverbs, and some conjunctions).
- Lowercase the conjunctions and, but, for, or, and nor.
- Lowercase the articles the, a, and an.
- Lowercase prepositions, regardless of length, except when they are stressed, are used adverbially or adjectivally, or are used as conjunctions.
- Lowercase the words to and as.
- Lowercase the second part of Latin species names.
- Lowercase the second word after a hyphenated prefix (e.g., Mid-, Anti-, Super-, etc.) in compound modifiers (e.g., Mid-year, Anti-hero, etc.).[5]
- Always capitalize the first and last words of titles and subtitles (overrides the rules above).
Modern Language Association (MLA) Handbook[edit]
According to the 9th edition of the Modern Language Association Handbook, the following title capitalization rules should be applied:[6]
- Capitalize the first word of the title/heading and of any subtitle/subheading.
- Capitalize all major words (nouns, verbs including phrasal verbs such as «play with», adjectives, adverbs, and pronouns) in the title/heading, including the second part of hyphenated major words (e.g., Self-Report not Self-report).
- Do not capitalize articles, prepositions (regardless of length), and coordinating conjunctions.
- Lowercase the second word after a hyphenated prefix (e.g., Mid-, Anti-, Super-, etc.) in compound modifiers (e.g., Mid-year, Anti-hero, etc.).
- Do not capitalize «to» in infinitives (e.g., I Want to Play Guitar).
APA Style[edit]
According to the 7th edition of the Publication Manual of the American Psychological Association, the following title capitalization rules should be applied:[6]
- Capitalize the first word of the title/heading and of any subtitle/subheading
- Capitalize all major words (nouns, verbs including phrasal verbs such as «play with», adjectives, adverbs, and pronouns) in the title/heading, including the second part of hyphenated major words (e.g., Self-Report not Self-report)
- Capitalize all words of four letters or more.
- Lowercase the second word after a hyphenated prefix (e.g., Mid-, Anti-, Super-, etc.) in compound modifiers (e.g., Mid-year, Anti-hero, etc.).
American Medical Association (AMA) Manual of Style Capitalization Rules[edit]
According to the 11th edition of the American Medical Association (AMA) Manual of Style, the following title capitalization rules should be applied:[6]
- Capitalize the first and the last word of titles and subtitles.
- Capitalize nouns, pronouns, adjectives, verbs (including phrasal verbs such as «play with»), adverbs, and subordinate conjunctions (major words).
- Lowercase articles (a, an, the), coordinating conjunctions, and prepositions of four letters or fewer.
- Lowercase «to» in infinitives.
- Lowercase the second word in a hyphenated compound when it is a prefix or suffix (e.g., «Anti-itch», «world-wide») or part of a single word.
- Capitalize the second word in a hyphenated compound if both words are equal and not suffices or prefixes (e.g., «Cost-Benefit»)
- Capitalize the first non-Greek letter after a lowercase Greek letter (e.g., «ω-Bromohexanoic»)
- Lowercase the first non-Greek letter after a capital Greek letter (e.g., «Δ-9-tetrahydrocannabinol»)
- Capitalize the genus but not the species epithet.
The Bluebook[edit]
According to the 21st edition of The Bluebook, used for legal citations, the following title capitalization rules should be applied:[6]
- Capitalize the first and the last word.
- Capitalize nouns, pronouns, adjectives, verbs (including phrasal verbs such as «play with»), adverbs, and subordinate conjunctions.
- Lowercase articles (a, an, the), coordinating conjunctions, and prepositions of four letters or fewer.
- Lowercase «to» in infinitives (though not defined in the stylebook).
Title case in references[edit]
The use of title case or sentence case in the references of scholarly publications is determined by the used citation style and can differ from the usage in title or headings. For example, APA Style uses sentence case for the title of the cited work in the list of references, but it uses title case for the title of the current publication (or for the title of a publication if it is mentioned in the text instead). Moreover, it uses title case for the title of periodicals even in the references.[7] Other citation styles like Chicago Manual of Style are using title case also for the title of cited works in the list of references.[8]
See also[edit]
- Sentence case
- Truecasing
References[edit]
- ^ «Title Capitalization Rules». Title Case Converter. Retrieved 16 September 2020.
- ^ The Associated Press Stylebook and Briefing on Media Law (46th ed.). New York: Basic Books. 2011. pp. 65–66. ISBN 9780465021871.
- ^ Title, Capitalize My (2021-04-25). «Title Capitalization Rules». Capitalize My Title. Retrieved 2022-06-13.
- ^ Grossman, John (2003). The Chicago Manual of Style (Fifteenth ed.). Chicago: University of Chicago Press. pp. 366–368. ISBN 0226104036.
- ^ «Title Capitalization Tool — Capitalize My Title — Title Case Tool». Capitalize My Title. Retrieved 2022-06-13.
- ^ a b c d «Title Capitalization Tool — Capitalize My Title — Title Case Tool». Capitalize My Title. Retrieved 2022-06-13.
- ^ Lee, Chelsea (2012-03-09). «APA Style 6th Edition Blog: Title Case and Sentence Case Capitalization in APA Style». blog.apastyle.org. Retrieved 2021-01-13.
- ^ «Why don’t titles show up in sentence case in bibliographies?». Zotero Documentation. Retrieved 2021-01-13.