Reputation: 2754
I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).
For instance, when the input is "I'm a little tea pot"
, I expect "I'm A Little Tea Pot"
to be the output. However, the function returns "i'm a little tea pot"
.
This is my code:
function titleCase(str) {
var splitStr = str.toLowerCase().split(" ");
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(" ");
}
return str;
}
console.log(titleCase("I'm a little tea pot"));
Upvotes: 255
Views: 383792
Reputation: 122878
Within my small es-string-fiddler utility I use this reducer. It also handles diacriticals and compound words (it's, hold-up).
const capitalizeWords = str => [...str.toLowerCase()]
.slice(1)
.reduce( (acc, v, i) =>
acc + ( !/\p{L}|['-]/u.test(acc.at(-1))
? v.toUpperCase() : v.toLowerCase() ),
str[0].toUpperCase() );
console.log(`HELLO WORLD => ${capitalizeWords(`HELLO WORLD`)}`);
console.log(`hello world => ${capitalizeWords(`hello world`)}`);
console.log(`I'm a little tea pot => ${
capitalizeWords(`I'm a little tea pot`)}`);
console.log(`I'm a little tea-pot, that's IT => ${
capitalizeWords(`I'm a little tea-pot, that's IT`)}`);
Upvotes: 0
Reputation: 155
This routine will handle hyphenated words and words with apostrophe.
function titleCase(text) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++) {
if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
if (text.charAt(i) == "'") {
if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1)))
firstLtr = 3;
else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2)))
firstLtr = 3;
}
if (firstLtr == 3)
firstLtr = 1;
else
firstLtr = 0;
}
if (firstLtr == 2) {
firstLtr = 1;
text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
}
else {
text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
}
}
return text;
}
titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";
Upvotes: 5
Reputation: 17
let str = "hi my name is raj"
function test(data){
let string = data.split(" ");
for(let i=0; i<string.length; i++ ){
string[i] = string[i][0].toUpperCase() + string[i].slice(1)
}
return string.join(" ")
}
console.log(test(str))
Upvotes: -1
Reputation: 1389
You can capitalize the first letter of a string in JavaScript by using some simple string and array functions. Here’s the complete code sample, followed by an explanation of how it works:
const greeting = "hello"
const capitalize = string => [
...string.slice(0, 1).toUpperCase(),
...string.slice(1)
].join("")
// Here's the same function, rewritten in long-form JavaScript
const capitalize = function(string) {
return [
...string.slice(0, 1).toUpperCase(),
...string.slice(1)
].join("")
}
capitalize(greeting) // "Hello"
This works by using slice to split the string by characters into two sections: the first character—using .slice(0, 1)—and the remainder of the string, with .slice(1). Without a second argument provided to slice, it will grab the rest of the string.
Strings can be coerced into arrays in JavaScript using the ES6 spread operator. By spreading the string into two sections, and calling .toUpperCase() on the first character, we can effectively capitalize the first letter of the string, and then join it back together inside of an array of characters. For instance:
const greeting = "hello"
const capitalizeWithoutJoin = string => [
...string.slice(0, 1).toUpperCase(),
...string.slice(1)
]
capitalizeWithoutJoin(greeting) // ["H", "e", "l", "l", "o"]
The spread operator takes both strings, and combines the array of characters from each into a single array, which is returned by the function. The original capitalize function takes that array of characters, and joins them back into a string.
The advantage of capitalizing the first letter of a string in this way is that you can re-use it for multiple words. For instance, if you want to capitalize the first letter of every word in a larger string, you can map through the words and call capitalize on each:
// const capitalize = string ...
const long_string = "hello world how is it going"
const capitalized = long_string.split(" ").map(string => capitalize(string)).join(" ")
capitalized // "Hello World How Is It Going"
(Originally posted on my blog: https://7.dev/javascript-capitalize-first-letter/)
Upvotes: 0
Reputation: 3703
There are many ways for achieving this, for instance you can try looping over string, or use JavaScript built in split()
, map()
and join()
I prefer using regex with replace method which is available on string
capitalize = (str) => {
return str.replace(/\b[a-z]/g, (letter) => letter.toUpperCase(););
}
identified using the \b boundary matcher and the [a-z] character class, and replaces it with the uppercase version of the letter using a callback function.
more efficient because it only iterates over the characters in the string once, and it uses a regular expression to identify the letters to be capitalized, which is generally faster than implementing the same logic using loops and string manipulation.
Upvotes: 5
Reputation: 7618
If practical, do make use of the text-transform: capitalize;
CSS property to convert the text to title case.
It is less expensive an operation compared to the JavaScript option in situations were you could equally rely on CSS to achieve the same result.
I'm A Little Tea Pot
is the result of the snippet below.
<p style="text-transform: capitalize;">I'm a little tea pot</p>
Upvotes: 4
Reputation: 430
With Regex and handling special characters like ñ
with multiple spaces in between : /(^.|\s+.)/g
let text = "ñora ñora"
console.log(text.toLowerCase().replace(/(^.|\s+.)/g, m => m.toUpperCase()))
Upvotes: 4
Reputation: 16597
function capitalizeFirstLetter(str) {
function isLetter(char) {
const code = char.charCodeAt(0);
// Considering apostrophe (char code 39) as a letter
return code > 64 && code < 91 || code > 96 && code < 123 || char.charCodeAt(0) === 39;
}
str = str.toLowerCase();
let newStr = '';
let processingWord = false;
for (let i = 0; i < str.length; i += 1) {
if (!processingWord && isLetter(str[i])) {
processingWord = true;
newStr += str[i].toUpperCase();
}
else {
newStr += str[i];
}
if (processingWord && !isLetter(str[i])) {
processingWord = false;
}
}
return newStr;
}
// stack overflow -> Stack Overflow
// ping-pong -> Ping-Pong
// domino's pizza -> Domino's Pizza
// /some/path -> /Some/Path
Upvotes: 0
Reputation: 171
This is a perfect example of using modern javascript practices to improve readability. Have not yet seen a reduce version here, but this is what i use. Its both a curried one-liner and very readable
sentence
.trim().toLowerCase()
.split(' ')
.reduce((sentence, word) => `${sentence} ${word[0].toUpperCase()}${word.substring(1)}`, '')
.trim()
Upvotes: 2
Reputation: 75
You can build upon this inputString[0].toUpperCase() + inputString.slice(1).toLowerCase()
:)
Upvotes: 1
Reputation:
Try This Function:
const capitializeName = (name) => {
const splitName = name.split(' ');
const namesUpper = [];
for (const n of splitName) {
namesUpper.push(n[0].toUpperCase() + n.slice(1));
}
console.log(namesUpper.join(' '));
};
capitializeName('jahid bhuiyan');
Upvotes: 0
Reputation: 751
var str = "hello world"
var result = str.split(" ").map(element => {
return element[0].toUpperCase() + element.slice(1);
});
result = result.join(" ")
console.log(result);
Upvotes: 1
Reputation: 22304
Shortest One Liner (also extremely fast):
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
Explanation:
^\w
: first character of the string|
: or\s\w
: first character after whitespace(^\w|\s\w)
Capture the pattern.g
Flag: Match all occurrences.If you want to make sure the rest is in lowercase:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
Example usage:
const toTitleCase = str => str.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
console.log(toTitleCase("heLLo worLd"));
Upvotes: 130
Reputation: 4199
I think this way should be faster; cause it doesn't split string and join it again; just using regex.
var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
Explanation:
(^\w{1})
: match first char of string|
: or(\s{1}\w{1})
: match one char that came after one spaceg
: match allUpvotes: 61
Reputation: 1497
Here a simple one-liner
const ucFirst = t => t.replace(/(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g, c => c.toUpperCase());
Note that it only changes case of first letter of every word, you might want to use it as so:
console.log(ucFirst('foO bAr'));
// FoO BAr
console.log(ucFirst('foO bAr'.toLowerCase()));
// Foo Bar
// works with accents too
console.log(ucFirst('éfoO bAr'));
// ÉfoO BAr
Or based on String.prototype
here is one that handles several modes:
String.prototype.ucFirst = function (mode = 'eachWord') {
const modes = {
eachWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g,
firstWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstChar: /^[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstLetter: /[A-Za-zÀ-ÖØ-öø-ÿ]/,
};
if (mode in modes) {
return this.replace(modes[mode], c => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: ` + Object.keys(modes).join('|');
}
};
console.log('eachWord', 'foO bAr'.ucFirst());
// FoO BAr
console.log('eachWord', 'foO bAr'.toLowerCase().ucFirst());
// Foo Bar
console.log('firstWord', '1foO bAr'.ucFirst('firstWord'));
// 1foO BAr
console.log('firstChar', '1foO bAr'.ucFirst('firstChar'));
// 1foO bAr
console.log('firstLetter', '1foO bAr'.ucFirst('firstLetter'));
// 1FoO bAr
Edit:
Or based on String.prototype
one that handles several modes and an optional second argument to specify word separators (String
or RegExp
):
String.prototype.ucFirst = function (mode = 'eachWord', wordSeparator = /\s/) {
const letters = /[A-Za-zÀ-ÖØ-öø-ÿ]/;
const ws =
'^|' +
(wordSeparator instanceof RegExp
? '(' + wordSeparator.source + ')'
: // sanitize string for RegExp https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex#comment52837041_6969486
'[' + wordSeparator.replace(/[[{}()*+?^$|\]\.\\]/g, '\\$&') + ']');
const r =
mode === 'firstLetter'
? letters
: mode === 'firstChar'
? new RegExp('^' + letters.source)
: mode === 'firstWord' || mode === 'eachWord'
? new RegExp(
'(' + ws + ')' + letters.source,
mode === 'eachWord' ? 'g' : undefined
)
: undefined;
if (r) {
return this.replace(r, (c) => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: firstLetter|firstChar|firstWord|eachWord`;
}
};
console.log("mike o'hara".ucFirst('eachWord', " \t\r\n\f\v'"));
// Mike O'Hara
console.log("mike o'hara".ucFirst('eachWord', /[\s']/));
// Mike O'Hara
Upvotes: 4
Reputation: 204
I have done this using this code below, hope it will help you:
<p id="p1">This is a paragraph.</p>
<script>
const capitalize = (mySentence) => {
const words = mySentence.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
return words.join(" ");
};
const result = capitalize('This is a sample text');
document.getElementById("p1").innerHTML = result;
</script>
Upvotes: 0
Reputation: 51
TypeScript fat arrow FTW
export const formatTitleCase = (string: string) =>
string
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.substring(1))
.join(" ");
Upvotes: 3
Reputation: 509
You could do it is simple way like this in one line with map with toUpperCase:
text.split(' ').map(w => { let t = w.split(''); t[0] = t[0].toUpperCase(); return t.join('') }).join(' ')
Upvotes: 0
Reputation: 1538
let string = "I'm a little tea pot";
Now, create a function that will take a string as an argument.
function titleCase(str) {
return str.split(" ").map(s => s.charAt(0).toUpperCase() + s.substr(1).toLowerCase()).join(" ")
}
Output
titleCase(string); // "I'm A Little Tea Pot"
Upvotes: 1
Reputation: 22158
You are making complex a very easy thing. You can add this in your CSS:
.capitalize {
text-transform: capitalize;
}
In JavaScript, you can add the class to an element
document.getElementById("element").className = "capitalize";
Upvotes: 197
Reputation:
ECMAScript 6 version:
title
.split(/ /g).map(word =>
`${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
.join(" ");
Upvotes: 16
Reputation: 83
You can use modern JS syntax which can make your life much easier. Here is my code snippet for the given problem:
const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')
Upvotes: 5
Reputation: 3224
This is a simple method to convert and is able to pass a value to get the desired output.
String.prototype.toChangeCase = function (type) {
switch (type) {
case 'upper-first':
return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
case 'upper-each':
return this.split(' ').map(word => {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
}).join(' ');
default:
throw Error(`In order to get the output pass a value 'upper-first', 'upper-each'`);
}
}
"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-first')
"Capitalize first letter of each word in a sstring"
"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-each')
"Capitalize First Letter Of Each Word In A Sstring"
"Capitalize First Letter Of Each Word In A String".toChangeCase()
VM380:12 Uncaught Error: In order to get the output pass a value 'upper-first', 'upper-each'
at String.toChangeCase (<anonymous>:12:19)
at <anonymous>:16:52
Upvotes: 0
Reputation: 1126
A complete and simple solution goes here:
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index
+ replacement.length);
}
var str = 'k j g u i l p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
for(let i = 0; i < str.length-1; i++) {
if(str[i] === ' ' && str[i+1] !== '')
str = str.replaceAt(i+1, str[i+1].toUpperCase());
}
return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));
Upvotes: 1
Reputation: 51
Below is another way to capitalize the first alphabet of each word in a string.
Create a custom method for a String object by using prototype
.
String.prototype.capitalize = function() {
var c = '';
var s = this.split(' ');
for (var i = 0; i < s.length; i++) {
c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
}
return c;
}
var name = "john doe";
document.write(name.capitalize());
Upvotes: 2
Reputation: 1152
In ECMAScript 6, a one-line answer using the arrow function:
const captialize = words => words.split(' ').map( w => w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
Upvotes: 23
Reputation: 59
Or it can be done using replace(), and replace each word's first letter with its "upperCase".
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
Upvotes: 4
Reputation: 89
Also a good option (particularly if you're using freeCodeCamp):
function titleCase(str) {
var wordsArray = str.toLowerCase().split(/\s+/);
var upperCased = wordsArray.map(function(word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});
return upperCased.join(" ");
}
Upvotes: 7
Reputation: 1631
I used replace()
with a regular expression:
function titleCase(str) {
var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());
console.log(newStr);
}
titleCase("I'm a little tea pot")
Upvotes: 1