Reputation: 18115
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.
Upvotes: 817
Views: 781369
Reputation: 839
For Angular / TypeScript using @Greg Dean answer
main.ts
declare global {
// eslint-disable-next-line id-blacklist
interface String {
toTitleCase(): string;
}
}
interface String {
toTitleCase(): string;
}
String.prototype.toTitleCase = function() {
return this.replace(
/\w\S*/g,
text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
);
};
Upvotes: -1
Reputation: 8027
Converting a text to titlecase consists in converting the initial of each word to uppercase and the remaining characters to lowercase. Initials are defined as word characters not preceded by word characters; they can be matched by a negative lookbehind assertion.
\s
, that is \S
):function toTitleCase(text, locale=navigator.language) {
return text.toLocaleLowerCase(locale).replace(
/(?<!\S)\S/ug, match => match.toLocaleUpperCase(locale)
);
}
toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–output ’til Out-of-memory'
\s
and not \p{Pd}
, that is [^\s\p{Pd}]
):function toTitleCase(text, locale=navigator.language) {
return text.toLocaleLowerCase(locale).replace(
/(?<![^\s\p{Pd}])[^\s\p{Pd}]/ug, match => match.toLocaleUpperCase(locale)
);
}
toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–Output ’til Out-Of-Memory'
Here is an alternative implementation based on the built-in Intl.Segmenter
API for segmenting sentences into words:
function toTitleCase(text, locale=navigator.language) {
const segmenter = new Intl.Segmenter(locale, { granularity: 'word' });
const capitalize = word => word.toLocaleLowerCase(locale).replace(
/^\p{CWU}/u, match => match.toLocaleUpperCase(locale)
);
return Array.from(
segmenter.segment(text),
segment => capitalize(segment.segment)
).join('');
}
toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–Output ’Til Out-Of-Memory'
Upvotes: 4
Reputation: 30057
Use:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
);
}
const example = 'john smith';
console.log(`"${example}" becomes "${toTitleCase(example)}"`);
Interactive example:
const input = document.querySelector('[name="input"]');
const output = document.querySelector('[name="output"]');
input.addEventListener('change', () => {
output.value = toTitleCase(input.value);
});
input.addEventListener('keyup', () => {
output.value = toTitleCase(input.value);
});
output.addEventListener('click', () => output.select());
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
);
}
<form>
Input: <br/>
<textarea name="input"></textarea>
<br/>
Output: <br/>
<textarea name="output" readonly></textarea>
</form>
Upvotes: 1009
Reputation: 54
var string = "tEsT"
string = string.toLowerCase()
var output= string.charAt(0).toUpperCase() + string.slice(1)
console.log(output)
alert(output)
var string = "tEsT"
string = string.toLowerCase()
string.charAt(0).toUpperCase() + string.slice(1)
Upvotes: 3
Reputation: 18888
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(/\b\w/g, s => s.toUpperCase());
}
console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));
Upvotes: 67
Reputation: 11396
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.
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(
/\w\S*/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
Upvotes: 42
Reputation: 121
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.
Upvotes: 5
Reputation: 1035
I highly recommend just using an open source NPM package if you can, this package works great in typescript:
NPM: https://www.npmjs.com/package/title-case
Github: https://github.com/blakeembrey/change-case/tree/master/packages/title-case#readme
Run npm install title-case
to add the package to your project.
Example Code using the title-case
npm package:
import { titleCase } from "title-case";
titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
Upvotes: 3
Reputation: 2734
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)
})
}
Upvotes: 9
Reputation: 9163
If you'd like to use an NPM library, check out title-case
:
Installation:
npm install title-case --save
Usage:
import { titleCase } from "title-case";
titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
Upvotes: 1
Reputation: 4072
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)
Upvotes: 352
Reputation: 9474
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);
Upvotes: 192
Reputation: 5854
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(/(\s\s+)/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.
Upvotes: 18
Reputation: 155
No regex, no loop, no split, no substring:
String.prototype.toTitleCase = function () { return this.valueOf().toLowerCase().replace(this.valueOf()[0], this.valueOf()[0].toUpperCase()); }
console.log('laiLA'.toTitleCase());
Upvotes: 0
Reputation: 437
My answer using regex.
for more details regex: https://regex101.com/r/AgRM3p/1
function toTitleCase(string = '') {
const regex = /^[a-z]{0,1}|\s\w/gi;
string = string.toLowerCase();
string.match(regex).forEach((char) => {
string = string.replace(char, char.toUpperCase());
});
return string;
}
const input = document.getElementById('fullname');
const button = document.getElementById('button');
const result = document.getElementById('result');
button.addEventListener('click', () => {
result.innerText = toTitleCase(input.value);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<input type="text" id="fullname">
<button id="button">click me</button>
<p id="result">Result here</p>
<script src="./index.js"></script>
</body>
</html>
Upvotes: -1
Reputation: 922
You can capitalize 1st char and join with the remaining string.
let str = 'john smith';
let res = str.split(" ");
res.forEach((w, index) => {
res[index] = w.charAt(0).toUpperCase().concat(w.slice(1, w.length))
});
res = res.join(" ");
console.log(res);
Upvotes: 3
Reputation: 2139
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(" ");
function titleCase(str) {
str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
var words = str.split(" ");
var capitalized = words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});
return capitalized.join(" ");
}
console.log(titleCase("I'm a little tea pot"));
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."));
Upvotes: 11
Reputation: 125
Here is my answer Guys Please comment and like if your problem solved.
function toTitleCase(str) {
return str.replace(
/(\w*\W*|\w*)\s*/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>
Upvotes: 2
Reputation: 1417
Here's a really simple & concise ES6 function to do this:
const titleCase = (str) => {
return str.replace(/\w\S*/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'
Upvotes: 5
Reputation: 1811
A one-liner using regex, get all \g
starting characters of words \b[a-zA-Z]
, and apply .toUpperCase()
const textString = "Convert string to title case with Javascript.";
const converted = textString.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());
console.log(converted)
Upvotes: 4
Reputation: 1903
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)
Upvotes: 26
Reputation: 208
Simple way to convert an individual word to title case
Using the "Slice" method and String concatenation
str.slice(0, 1).toUpperCase() + str.slice(1, str.length)
*Add .toLowerCase() to the end if you want to lowercase the rest of the word
Using ES6 Spread Operator, Map, and Join
[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')
Upvotes: 4
Reputation: 5510
My list is based on three quick searches. One for a list of words not to be capitalized, and one for a full list of prepositions.
One final search made the suggestion that prepositions 5 letters or longer should be capitalized, which is something I liked. My purpose is for informal use. I left 'without' in their, because it's the obvious counterpart to with.
So it capitalizes acronyms, the first letter of the title, and the first letter of most words.
It is not intended to handle words in caps-lock. I wanted to leave those alone.
function camelCase(str) {
return str.replace(/((?:^|\.)\w|\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\b)\w)/g, function(character) {
return character.toUpperCase();
})}
console.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));
Upvotes: 2
Reputation: 7509
I think you should try with this function.
var toTitleCase = function (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(' ');
};
Upvotes: -1
Reputation: 1551
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:
String.prototype.toTitle = function() {
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}
console.log('all lower case ->','all lower case'.toTitle());
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
Upvotes: 62
Reputation: 15488
var result =
'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())
console.log(result) // This Is Very Interesting
Upvotes: 26
Reputation: 779
A solution using lodash -
import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';
const titleCase = string =>
padEnd(
words(string, /[^ ]+/g)
.map(lowerCase)
.map(capitalize)
.join(' '),
string.length,
);
Upvotes: 1
Reputation: 1623
My one line solution:
String.prototype.capitalizeWords = function() {
return this.split(" ").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(" ");
};
Then, you can call the method capitalizeWords()
on any string. For example:
var myS = "this actually works!";
myS.capitalizeWords();
>>> This Actually Works
My other solution:
function capitalizeFirstLetter(word) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeAllWords = function() {
var arr = this.split(" ");
for(var i = 0; i < arr.length; i++) {
arr[i] = capitalizeFirstLetter(arr[i]);
}
return arr.join(" ");
};
Then, you can call the method capitalizeWords()
on any string. For example:
var myStr = "this one works too!";
myStr.capitalizeWords();
>>> This One Works Too
Alternative solution based on Greg Dean answer:
function capitalizeFirstLetter(word) {
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeWords = function() {
return this.replace(/\w\S*/g, capitalizeFirstLetter);
};
Then, you can call the method capitalizeWords()
on any string. For example:
var myString = "yes and no";
myString.capitalizeWords()
>>> Yes And No
Upvotes: 4
Reputation: 435
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()
)
Upvotes: 21