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.
This question is related to
javascript
title-case
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(' ')
A method use reduce
function titleCase(str) {_x000D_
const arr = str.split(" ");_x000D_
const result = arr.reduce((acc, cur) => {_x000D_
const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();_x000D_
return acc += `${newStr} `_x000D_
},"")_x000D_
return result.slice(0, result.length-1);_x000D_
}
_x000D_
Robust Functional programming way to do Title Case Function
Exaplin Version
function toTitleCase(input){
let output = input
.split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
.map((letter) => {
let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y
let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
return firstLetter + restLetters // conbine together
})
.join(' ') //['How' 'Are' 'You'] => 'How Are You'
return output
}
Implementation version
function toTitleCase(input){
return input
.split(' ')
.map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
.join(' ')
}
toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
A method use reduce
function titleCase(str) {_x000D_
const arr = str.split(" ");_x000D_
const result = arr.reduce((acc, cur) => {_x000D_
const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();_x000D_
return acc += `${newStr} `_x000D_
},"")_x000D_
return result.slice(0, result.length-1);_x000D_
}
_x000D_
Try this, shortest way:
str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
We have been having a discussion back here at the office and we think that trying to automatically correct the way people input names in the current way you want it doing is fraught with possible issues.
We have come up with several cases where different types of auto capitalization fall apart and these are just for English names alone, each language has its own complexities.
Issues with capitalizing the first letter of each name:
• Acronyms such as IBM aren’t allowed to be inputted, would turn into Ibm.
• The Name McDonald would turn into Mcdonald which is incorrect, the same thing is MacDonald too.
• Double barrelled names such as Marie-Tonks would get turned into Marie-tonks.
• Names like O’Connor would turn into O’connor.
For most of these you could write custom rules to deal with it, however, this still has issues with Acronyms as before and you get a new issue:
• Adding in a rule to fix names with Mac such as MacDonald, would the break names such as Macy turning it into MacY.
The only solution we have come up with that is never incorrect is to capitalize every letter which is a brute force method that the DBS appear to also use.
So if you want to automate the process it is as good as impossible to do without a dictionary of every single name and word and how it should be capitlized, If you don't have a rule that covers everything don't use it as it will just annoy your users and prompt people who want to enter their names correctly to go else where.
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;
}
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
Taking the "lewax00" solution I created this simple solution that force to "w" starting with space or "w" that initiate de word, but is not able to remove the extra intermediate spaces.
"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });
_x000D_
The result is "Sofía Vergara".
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 !
This is based on my solution for FreeCodeCamp's Bonfire "Title Case", which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.
Without using regex:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}
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,
);
I think the simplest is using css.
function format_str(str) {
str = str.toLowerCase();
return '<span style="text-transform: capitalize">'+ str +'</span>';
}
Just another version to add to the mix. This will also check if the string.length is 0:
String.prototype.toTitleCase = function() {
var str = this;
if(!str.length) {
return "";
}
str = str.split(" ");
for(var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
}
return (str.length ? str.join(" ") : str);
};
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:"
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(' ');
}
My simple and easy version to the problem:
function titlecase(str){
var arr=[];
var str1=str.split(' ');
for (var i = 0; i < str1.length; i++) {
var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
arr.push(upper);
};
return arr.join(' ');
}
titlecase('my name is suryatapa roy');
For those of us who are scared of regular expressions (lol):
function titleCase(str)_x000D_
{_x000D_
var words = str.split(" ");_x000D_
for ( var i = 0; i < words.length; i++ )_x000D_
{_x000D_
var j = words[i].charAt(0).toUpperCase();_x000D_
words[i] = j + words[i].substr(1);_x000D_
}_x000D_
return words.join(" ");_x000D_
}
_x000D_
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();
I wanted to add my own answer as I needed a robust toTitleCase
function that takes into account grammar rules listed here (Google recommended article). There are various rules that depend on the length of the input string. Below is the function + unit tests.
The function also consolidates whitespace and removes special characters (modify regex for your needs)
toTitleCase Function
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.
Another approach to achieve something similar can be as follows.
formatName(name) {
let nam = '';
name.split(' ').map((word, index) => {
if (index === 0) {
nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
} else {
nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
}
});
return nam;
}
Try this:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
_x000D_
<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>
_x000D_
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())
}
);
}
_x000D_
<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>
_x000D_
Without using regex just for reference:
String.prototype.toProperCase = function() {_x000D_
var words = this.split(' ');_x000D_
var results = [];_x000D_
for (var i = 0; i < words.length; i++) {_x000D_
var letter = words[i].charAt(0).toUpperCase();_x000D_
results.push(letter + words[i].slice(1));_x000D_
}_x000D_
return results.join(' ');_x000D_
};_x000D_
_x000D_
console.log(_x000D_
'john smith'.toProperCase()_x000D_
)
_x000D_
This is one line solution, if you want convert every work in the string, Split the string by " ", iterate over the parts and apply this solution to each part, add every converted part to a array and join it with " ".
var stringToConvert = 'john';_x000D_
stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');_x000D_
console.log(stringToConvert);
_x000D_
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) {_x000D_
return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());_x000D_
}_x000D_
_x000D_
console.log(titleCase('iron man'));_x000D_
console.log(titleCase('iNcrEdible hulK'));
_x000D_
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 !
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,
);
Prototype solution of Greg Dean's solution:
String.prototype.capitalize = function() {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
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'
I wanted to add my own answer as I needed a robust toTitleCase
function that takes into account grammar rules listed here (Google recommended article). There are various rules that depend on the length of the input string. Below is the function + unit tests.
The function also consolidates whitespace and removes special characters (modify regex for your needs)
toTitleCase Function
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.
Taking the "lewax00" solution I created this simple solution that force to "w" starting with space or "w" that initiate de word, but is not able to remove the extra intermediate spaces.
"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });
_x000D_
The result is "Sofía Vergara".
This is one line solution, if you want convert every work in the string, Split the string by " ", iterate over the parts and apply this solution to each part, add every converted part to a array and join it with " ".
var stringToConvert = 'john';_x000D_
stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');_x000D_
console.log(stringToConvert);
_x000D_
Here is a compact solution to the problem:
function Title_Case(phrase)
{
var revised = phrase.charAt(0).toUpperCase();
for ( var i = 1; i < phrase.length; i++ ) {
if (phrase.charAt(i - 1) == " ") {
revised += phrase.charAt(i).toUpperCase(); }
else {
revised += phrase.charAt(i).toLowerCase(); }
}
return revised;
}
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(); });
}
Robust Functional programming way to do Title Case Function
Exaplin Version
function toTitleCase(input){
let output = input
.split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
.map((letter) => {
let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y
let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
return firstLetter + restLetters // conbine together
})
.join(' ') //['How' 'Are' 'You'] => 'How Are You'
return output
}
Implementation version
function toTitleCase(input){
return input
.split(' ')
.map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
.join(' ')
}
toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
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)
_x000D_
Here's my version, IMO it's easy to understand and elegant too.
var str = "foo bar baz"_x000D_
_x000D_
console.log(_x000D_
_x000D_
str.split(' ')_x000D_
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())_x000D_
.join(' ')_x000D_
_x000D_
)_x000D_
// returns "Foo Bar Baz"
_x000D_
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');_x000D_
// => 'Foo Bar'_x000D_
_x000D_
_.startCase('--foo-bar--');_x000D_
// => 'Foo Bar'_x000D_
_x000D_
_.startCase('fooBar');_x000D_
// => 'Foo Bar'_x000D_
_x000D_
_.startCase('__FOO_BAR__');_x000D_
// => 'FOO BAR'
_x000D_
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(' ');
};
ES6 one liner
const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');
Try this:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
_x000D_
<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>
_x000D_
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;}
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'
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
There's been some great answers, but, with many people using regex to find the word, but, for some reason, nobody else uses regex to replace the first character. For explanation, I'll provide a long solution and a shorter one.
The long solution (more explanatory). By using regular expression [^\s_\-/]*
we can find every word in the sentence. Subsequently, we can use the regular expression .
to match to the first character in a word. Using the regular expression version of replace for both of these, we can change the solution like this:
function toUpperCase(str) { return str.toUpperCase(); }_x000D_
function capitalizeWord(word) { return word.replace(/./, toUpperCase); }_x000D_
function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); }_x000D_
_x000D_
console.log(capitalize("hello world")); // Outputs: Hello World
_x000D_
For a single function that does the same thing, we nest the replace
calls as follows:
function capitalize(sentence) {_x000D_
return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) {_x000D_
return word.replace(/./, function (ch) { return ch.toUpperCase(); } );_x000D_
} );_x000D_
}_x000D_
_x000D_
console.log(capitalize("hello world")); // Outputs: Hello World
_x000D_
function titleCase(str) {
str = str.toLowerCase();
var strArray = str.split(" ");
for(var i = 0; i < strArray.length; i++){
strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);
}
var result = strArray.join(" ");
//Return the string
return result;
}
function toTitleCase(str) {
var strnew = "";
var i = 0;
for (i = 0; i < str.length; i++) {
if (i == 0) {
strnew = strnew + str[i].toUpperCase();
} else if (i != 0 && str[i - 1] == " ") {
strnew = strnew + str[i].toUpperCase();
} else {
strnew = strnew + str[i];
}
}
alert(strnew);
}
toTitleCase("hello world how are u");
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(' ')
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(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}
Works for hyphenated names like Jim-Bob too.
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) {_x000D_
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) {_x000D_
return character.toUpperCase();_x000D_
})}_x000D_
_x000D_
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.'));
_x000D_
As full featured as John Resig's solution, but as a one-liner: (based on this github project)
function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};
console.log( toTitleCase( "ignores mixed case words like iTunes, and allows AT&A and website.com/address etc..." ) );
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(' ');
}
Here's my version, IMO it's easy to understand and elegant too.
var str = "foo bar baz"_x000D_
_x000D_
console.log(_x000D_
_x000D_
str.split(' ')_x000D_
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())_x000D_
.join(' ')_x000D_
_x000D_
)_x000D_
// returns "Foo Bar Baz"
_x000D_
Try to apply the text-transform CSS style to your controls.
eg: (text-transform: capitalize);
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"_x000D_
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")_x000D_
console.log(str)
_x000D_
As full featured as John Resig's solution, but as a one-liner: (based on this github project)
function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};
console.log( toTitleCase( "ignores mixed case words like iTunes, and allows AT&A and website.com/address etc..." ) );
A slightly more elegant way, adapting Greg Dean's function:
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Call it like:
"pascal".toProperCase();
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.
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;
});
};
Simpler more performant version, with simple caching.
var TITLE_CASE_LOWER_MAP = {_x000D_
'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,_x000D_
'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1_x000D_
};_x000D_
_x000D_
// LEAK/CACHE TODO: evaluate using LRU._x000D_
var TITLE_CASE_CACHE = new Object();_x000D_
_x000D_
toTitleCase: function (title) {_x000D_
if (!title) return null;_x000D_
_x000D_
var result = TITLE_CASE_CACHE[title];_x000D_
if (result) {_x000D_
return result;_x000D_
}_x000D_
_x000D_
result = "";_x000D_
var split = title.toLowerCase().split(" ");_x000D_
for (var i=0; i < split.length; i++) {_x000D_
_x000D_
if (i > 0) {_x000D_
result += " ";_x000D_
}_x000D_
_x000D_
var word = split[i];_x000D_
if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {_x000D_
word = word.substr(0,1).toUpperCase() + word.substr(1);_x000D_
}_x000D_
_x000D_
result += word;_x000D_
}_x000D_
_x000D_
TITLE_CASE_CACHE[title] = result;_x000D_
_x000D_
return result;_x000D_
},
_x000D_
ES-6 way to get title case of a word or entire line.
ex. input = 'hEllo' --> result = 'Hello'
ex. input = 'heLLo woRLd' --> result = 'Hello World'
const getTitleCase = (str) => {
if(str.toLowerCase().indexOf(' ') > 0) {
return str.toLowerCase().split(' ').map((word) => {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
else {
return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
}
}
var result =_x000D_
'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())_x000D_
_x000D_
console.log(result) // This Is Very Interesting
_x000D_
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;
}
String.prototype.capitalize = function() {
return this.toLowerCase().split(' ').map(capFirst).join(' ');
function capFirst(str) {
return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
}
}
Usage:
"hello world".capitalize()
https://lodash.com/docs/4.17.11#capitalize
Use Lodash Library..!! More Reliable
_.capitalize('FRED'); => 'Fred'
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
var result =_x000D_
'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())_x000D_
_x000D_
console.log(result) // This Is Very Interesting
_x000D_
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())
}
);
}
_x000D_
<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>
_x000D_
function toTitleCase(str) {
var strnew = "";
var i = 0;
for (i = 0; i < str.length; i++) {
if (i == 0) {
strnew = strnew + str[i].toUpperCase();
} else if (i != 0 && str[i - 1] == " ") {
strnew = strnew + str[i].toUpperCase();
} else {
strnew = strnew + str[i];
}
}
alert(strnew);
}
toTitleCase("hello world how are u");
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');_x000D_
// => 'Foo Bar'_x000D_
_x000D_
_.startCase('--foo-bar--');_x000D_
// => 'Foo Bar'_x000D_
_x000D_
_.startCase('fooBar');_x000D_
// => 'Foo Bar'_x000D_
_x000D_
_.startCase('__FOO_BAR__');_x000D_
// => 'FOO BAR'
_x000D_
It's not short but here is what I came up with on a recent assignment in school:
var myPoem = 'What is a jQuery but a misunderstood object?'_x000D_
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?_x000D_
_x000D_
//code here_x000D_
var capitalize = function(str) {_x000D_
var strArr = str.split(' ');_x000D_
var newArr = [];_x000D_
for (var i = 0; i < strArr.length; i++) {_x000D_
newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))_x000D_
};_x000D_
return newArr.join(' ') _x000D_
}_x000D_
_x000D_
var fixedPoem = capitalize(myPoem);_x000D_
alert(fixedPoem);
_x000D_
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
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)
_x000D_
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) {_x000D_
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) {_x000D_
return character.toUpperCase();_x000D_
})}_x000D_
_x000D_
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.'));
_x000D_
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"_x000D_
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")_x000D_
console.log(str)
_x000D_
We have been having a discussion back here at the office and we think that trying to automatically correct the way people input names in the current way you want it doing is fraught with possible issues.
We have come up with several cases where different types of auto capitalization fall apart and these are just for English names alone, each language has its own complexities.
Issues with capitalizing the first letter of each name:
• Acronyms such as IBM aren’t allowed to be inputted, would turn into Ibm.
• The Name McDonald would turn into Mcdonald which is incorrect, the same thing is MacDonald too.
• Double barrelled names such as Marie-Tonks would get turned into Marie-tonks.
• Names like O’Connor would turn into O’connor.
For most of these you could write custom rules to deal with it, however, this still has issues with Acronyms as before and you get a new issue:
• Adding in a rule to fix names with Mac such as MacDonald, would the break names such as Macy turning it into MacY.
The only solution we have come up with that is never incorrect is to capitalize every letter which is a brute force method that the DBS appear to also use.
So if you want to automate the process it is as good as impossible to do without a dictionary of every single name and word and how it should be capitlized, If you don't have a rule that covers everything don't use it as it will just annoy your users and prompt people who want to enter their names correctly to go else where.
Try this:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
_x000D_
<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>
_x000D_
Try this, shortest way:
str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
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();
String.prototype.capitalize = function() {
return this.toLowerCase().split(' ').map(capFirst).join(' ');
function capFirst(str) {
return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
}
}
Usage:
"hello world".capitalize()
Another approach to achieve something similar can be as follows.
formatName(name) {
let nam = '';
name.split(' ').map((word, index) => {
if (index === 0) {
nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
} else {
nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
}
});
return nam;
}
This is based on my solution for FreeCodeCamp's Bonfire "Title Case", which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.
Without using regex:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}
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();
});
}
Prototype solution of Greg Dean's solution:
String.prototype.capitalize = function() {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
this is a test
---> This Is A Test
function capitalize(str) {_x000D_
_x000D_
const word = [];_x000D_
_x000D_
for (let char of str.split(' ')) {_x000D_
word.push(char[0].toUpperCase() + char.slice(1))_x000D_
}_x000D_
_x000D_
return word.join(' ');_x000D_
_x000D_
}_x000D_
_x000D_
console.log(capitalize("this is a test"));
_x000D_
ES6 one liner
const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');
For those of us who are scared of regular expressions (lol):
function titleCase(str)_x000D_
{_x000D_
var words = str.split(" ");_x000D_
for ( var i = 0; i < words.length; i++ )_x000D_
{_x000D_
var j = words[i].charAt(0).toUpperCase();_x000D_
words[i] = j + words[i].substr(1);_x000D_
}_x000D_
return words.join(" ");_x000D_
}
_x000D_
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(); });
}
This solution takes punctuation into account for new sentences, handles quotations, converts minor words to lowercase and ignores acronyms or all-caps words.
var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");
// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
var newSentence = true;
return this.split(/\s+/).map(function(word) {
if (word == "") { return; }
var canCapitalise = true;
// Get the pos of the first alpha char (word might start with " or ')
var firstAlphaCharPos = word.search(/\w/);
// Check for uppercase char that is not the first char (might be acronym or all caps)
if (word.search(/[A-Z]/) > 0) {
canCapitalise = false;
} else if (stopWordsArray.indexOf(word) != -1) {
// Is a stop word and not a new sentence
word.toLowerCase();
if (!newSentence) {
canCapitalise = false;
}
}
// Is this the last word in a sentence?
newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
}).join(' ');
}
// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());
/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
Try this:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
_x000D_
<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>
_x000D_
There's been some great answers, but, with many people using regex to find the word, but, for some reason, nobody else uses regex to replace the first character. For explanation, I'll provide a long solution and a shorter one.
The long solution (more explanatory). By using regular expression [^\s_\-/]*
we can find every word in the sentence. Subsequently, we can use the regular expression .
to match to the first character in a word. Using the regular expression version of replace for both of these, we can change the solution like this:
function toUpperCase(str) { return str.toUpperCase(); }_x000D_
function capitalizeWord(word) { return word.replace(/./, toUpperCase); }_x000D_
function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); }_x000D_
_x000D_
console.log(capitalize("hello world")); // Outputs: Hello World
_x000D_
For a single function that does the same thing, we nest the replace
calls as follows:
function capitalize(sentence) {_x000D_
return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) {_x000D_
return word.replace(/./, function (ch) { return ch.toUpperCase(); } );_x000D_
} );_x000D_
}_x000D_
_x000D_
console.log(capitalize("hello world")); // Outputs: Hello World
_x000D_
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.
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;
});
};
My simple and easy version to the problem:
function titlecase(str){
var arr=[];
var str1=str.split(' ');
for (var i = 0; i < str1.length; i++) {
var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
arr.push(upper);
};
return arr.join(' ');
}
titlecase('my name is suryatapa roy');
Use /\S+/g
to support diacritics:
function toTitleCase(str) {_x000D_
return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());_x000D_
}_x000D_
_x000D_
console.log(toTitleCase("a city named örebro")); // A City Named Örebro
_x000D_
However: "sunshine (yellow)" ? "Sunshine (yellow)"
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() {_x000D_
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });_x000D_
}_x000D_
_x000D_
console.log('all lower case ->','all lower case'.toTitle());_x000D_
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());_x000D_
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
_x000D_
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('')
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();
});
}
Just another version to add to the mix. This will also check if the string.length is 0:
String.prototype.toTitleCase = function() {
var str = this;
if(!str.length) {
return "";
}
str = str.split(" ");
for(var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
}
return (str.length ? str.join(" ") : str);
};
Without using regex just for reference:
String.prototype.toProperCase = function() {_x000D_
var words = this.split(' ');_x000D_
var results = [];_x000D_
for (var i = 0; i < words.length; i++) {_x000D_
var letter = words[i].charAt(0).toUpperCase();_x000D_
results.push(letter + words[i].slice(1));_x000D_
}_x000D_
return results.join(' ');_x000D_
};_x000D_
_x000D_
console.log(_x000D_
'john smith'.toProperCase()_x000D_
)
_x000D_
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(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}
Works for hyphenated names like Jim-Bob too.
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(' ');
};
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:"
It's not short but here is what I came up with on a recent assignment in school:
var myPoem = 'What is a jQuery but a misunderstood object?'_x000D_
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?_x000D_
_x000D_
//code here_x000D_
var capitalize = function(str) {_x000D_
var strArr = str.split(' ');_x000D_
var newArr = [];_x000D_
for (var i = 0; i < strArr.length; i++) {_x000D_
newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))_x000D_
};_x000D_
return newArr.join(' ') _x000D_
}_x000D_
_x000D_
var fixedPoem = capitalize(myPoem);_x000D_
alert(fixedPoem);
_x000D_
Here is a compact solution to the problem:
function Title_Case(phrase)
{
var revised = phrase.charAt(0).toUpperCase();
for ( var i = 1; i < phrase.length; i++ ) {
if (phrase.charAt(i - 1) == " ") {
revised += phrase.charAt(i).toUpperCase(); }
else {
revised += phrase.charAt(i).toLowerCase(); }
}
return revised;
}
This solution takes punctuation into account for new sentences, handles quotations, converts minor words to lowercase and ignores acronyms or all-caps words.
var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");
// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
var newSentence = true;
return this.split(/\s+/).map(function(word) {
if (word == "") { return; }
var canCapitalise = true;
// Get the pos of the first alpha char (word might start with " or ')
var firstAlphaCharPos = word.search(/\w/);
// Check for uppercase char that is not the first char (might be acronym or all caps)
if (word.search(/[A-Z]/) > 0) {
canCapitalise = false;
} else if (stopWordsArray.indexOf(word) != -1) {
// Is a stop word and not a new sentence
word.toLowerCase();
if (!newSentence) {
canCapitalise = false;
}
}
// Is this the last word in a sentence?
newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
}).join(' ');
}
// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());
/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
Use /\S+/g
to support diacritics:
function toTitleCase(str) {_x000D_
return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());_x000D_
}_x000D_
_x000D_
console.log(toTitleCase("a city named örebro")); // A City Named Örebro
_x000D_
However: "sunshine (yellow)" ? "Sunshine (yellow)"
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();
});
}
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() {_x000D_
return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });_x000D_
}_x000D_
_x000D_
console.log('all lower case ->','all lower case'.toTitle());_x000D_
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());_x000D_
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
_x000D_
I think the simplest is using css.
function format_str(str) {
str = str.toLowerCase();
return '<span style="text-transform: capitalize">'+ str +'</span>';
}
this is a test
---> This Is A Test
function capitalize(str) {_x000D_
_x000D_
const word = [];_x000D_
_x000D_
for (let char of str.split(' ')) {_x000D_
word.push(char[0].toUpperCase() + char.slice(1))_x000D_
}_x000D_
_x000D_
return word.join(' ');_x000D_
_x000D_
}_x000D_
_x000D_
console.log(capitalize("this is a test"));
_x000D_
function titleCase(str) {
str = str.toLowerCase();
var strArray = str.split(" ");
for(var i = 0; i < strArray.length; i++){
strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);
}
var result = strArray.join(" ");
//Return the string
return result;
}
https://lodash.com/docs/4.17.11#capitalize
Use Lodash Library..!! More Reliable
_.capitalize('FRED'); => 'Fred'
ES-6 way to get title case of a word or entire line.
ex. input = 'hEllo' --> result = 'Hello'
ex. input = 'heLLo woRLd' --> result = 'Hello World'
const getTitleCase = (str) => {
if(str.toLowerCase().indexOf(' ') > 0) {
return str.toLowerCase().split(' ').map((word) => {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
else {
return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
}
}
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;}
A slightly more elegant way, adapting Greg Dean's function:
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Call it like:
"pascal".toProperCase();
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('')
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"));
_x000D_
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 my 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.") );
_x000D_
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."));
_x000D_
john smith -> John Smith
'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );
Simpler more performant version, with simple caching.
var TITLE_CASE_LOWER_MAP = {_x000D_
'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,_x000D_
'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1_x000D_
};_x000D_
_x000D_
// LEAK/CACHE TODO: evaluate using LRU._x000D_
var TITLE_CASE_CACHE = new Object();_x000D_
_x000D_
toTitleCase: function (title) {_x000D_
if (!title) return null;_x000D_
_x000D_
var result = TITLE_CASE_CACHE[title];_x000D_
if (result) {_x000D_
return result;_x000D_
}_x000D_
_x000D_
result = "";_x000D_
var split = title.toLowerCase().split(" ");_x000D_
for (var i=0; i < split.length; i++) {_x000D_
_x000D_
if (i > 0) {_x000D_
result += " ";_x000D_
}_x000D_
_x000D_
var word = split[i];_x000D_
if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {_x000D_
word = word.substr(0,1).toUpperCase() + word.substr(1);_x000D_
}_x000D_
_x000D_
result += word;_x000D_
}_x000D_
_x000D_
TITLE_CASE_CACHE[title] = result;_x000D_
_x000D_
return result;_x000D_
},
_x000D_
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) {_x000D_
return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());_x000D_
}_x000D_
_x000D_
console.log(titleCase('iron man'));_x000D_
console.log(titleCase('iNcrEdible hulK'));
_x000D_
john smith -> John Smith
'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );
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();
});
}
Try to apply the text-transform CSS style to your controls.
eg: (text-transform: capitalize);
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"));
_x000D_
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 my 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.") );
_x000D_
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."));
_x000D_
Source: Stackoverflow.com