How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters?
For example:
"this is a test"
→"This is a test"
"the Eiffel Tower"
→"The Eiffel Tower"
"/index.html"
→"/index.html"
How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters?
For example:
"this is a test"
→ "This is a test"
"the Eiffel Tower"
→ "The Eiffel Tower"
"/index.html"
→ "/index.html"
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
EDIT: Regexp is overkill for this, prefer the simpler : str.charAt(0).toUpperCase() + str.substring(1)
Only because this is really a one-liner I will include this answer. It's an ES6-based interpolated string one-liner.
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
The ucfirst
function works if you do it like this.
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
Thanks J-P for the aclaration.
string[0].toUpperCase() + string.substring(1)
Commented
Nov 25, 2015 at 4:01
You can do it in one line like this
string[0].toUpperCase() + string.substring(1)
Here's my version. I think it's easy to understand and elegant too.
var str = "foo bar baz";
// Capitalize
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
// Returns "Foo Bar Baz"
// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"
A functional approach
const capitalize = ([s, ...tring]) =>
[s.toUpperCase(), ...tring]
.join('');
Then you could
const titleCase = str =>
str
.split(' ')
.map(capitalize)
.join(' ')
In CoffeeScript, add to the prototype for a string:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
Usage would be:
"woobie".capitalize()
Which yields:
"Woobie"
String.prototype.capitalize = function () { return this.substring(0,1).toUpperCase() + this.substring(1).toLowerrCase() }
CoffeeScript is a little language that compiles into JavaScript.
Furthermore, The golden rule of CoffeeScript is: "It's just JavaScript."
I think if someone truly understands those two sentences, you'll understand why I included this answer. Hopefully that cleared things up for everyone. Source: coffeescript.org
Posting an edit of @salim's answer to include locale letter transformation.
var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);
str = str.charAt(0).toLocaleUpperCase() + str.substr(1);
, though, to make this shorter
The first character of every string is capitalized.
function capitalize(word){
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
console.log(capitalize("john")); //John
console.log(capitalize("BRAVO")); //Bravo
console.log(capitalize("BLAne")); //Blane
ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)
As a String prototype method:
String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
function capitalize(string) {
return string.replace(/^./, Function.call.bind("".toUpperCase));
}
^
asserts position at start. then .
matches a single character
Commented
Jun 28, 2018 at 16:51
Using the JS replace string method & a regular expression w/ a word boundary seems simple.
Capitalize the first words' first character: "the eiffel tower" --> "The eiffel tower"
str.replace(/\b\w/, v => v.toUpperCase())
Capitalize all words' first character: "the eiffel tower" --> "The Eiffel Tower"
str.replace(/\b\w/g, v => v.toUpperCase())
Here are a few suggestions to make a universal function that can capitalize only the first letter, or the first letter of each word, including words separated by a dash or other separators (like some first names in French).
By default, the function capitalizes only the first letter of the whole string, and leave the rest untouched.
Parameters:
1. No regex version
function capitalize( str, lc, all ) {
if( all ) {
return str.split( " " )
.map( word => capitalize( word, lc ) )
.join( " " )
.split( "-" )
.map( word => capitalize( word, false ) )
.join( "-" );
} else {
return lc
? str.charAt( 0 ).toUpperCase() + str.slice( 1 ).toLowerCase()
: str.charAt( 0 ).toUpperCase() + str.slice( 1 );
}
}
2. Using regex
function capitalize( str, lc, all ) {
const replacer =
lc ? ( m, p1, p2 ) => p1.toUpperCase() + p2.toLowerCase()
: ( m, p1, p2 ) => p1.toUpperCase() + p2;
if( all ) {
return str.split( /(\s|-|')/ )
.map( s => s.replace( /^([A-Za-zÀ-ÖØ-öø-ÿ])(.*)$/, replacer ) )
.join( "" )
} else {
return str.replace( /^([A-Za-zÀ-ÖØ-öø-ÿ])(.*)$/, replacer )
}
}
3. Alternative with rest parameters
function capitalizeWord( [first, ...rest], lc ) {
return first.toUpperCase() + ( lc ? rest.join("").toLowerCase() : rest.join("") );
}
function capitalize( str, lc, all ) {
return all ? str.split( /(\s|-|')/ )
.map( s => capitalizeWord( s, lc ) )
.join( "" )
: capitalizeWord( str, lc );
}
Examples
capitalize( "saiNT-jEAn d'anGÉly", false, false )
// returns "SaiNT-jEAn d'anGÉly"
capitalize( "saiNT-jEAn d'anGÉly", false, true )
// returns "SaiNT-JEAn D'AnGÉly"
capitalize( "saiNT-jEAn d'anGÉly", true, false )
// returns "Saint-jean d'angély"
capitalize( "saiNT-jEAn d'anGÉly", true, true )
// returns "Saint-Jean D'Angély"
// Uppercase first letter
function ucfirst(field) {
field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}
Usage:
<input type="text" onKeyup="ucfirst(this)" />
field.value
could be shortened with a variable for readability.
If you go with one of the regex answers, remember they will only work with ASCII characters. All your unicode letters will not be uppercased. The XRegExp library and its unicode plugins solve this problem if you want to stick with regexps. So something like this would work:
String.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
Considering that it still doesn't cover all possibilities (combined characters, see http://www.regular-expressions.info/unicode.html) it seems easier to just use the .charAt(0).toUpperCase() approach.
Or you could use Sugar.js capitalize()
Example:
'hello'.capitalize() -> 'Hello'
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
One possible solution:
function ConvertFirstCharacterToUpperCase(text) {
return text.substr(0, 1).toUpperCase() + text.substr(1);
}
Use this:
alert(ConvertFirstCharacterToUpperCase("this is string"));
Here is working JS Fiddle
Using current language features:
function capitalize([firstLetter, ...rest]) {
return [firstLetter.toLocaleUpperCase(), ...rest].join('');
}
console.log(capitalize('foo bar'));
console.log(capitalize('ѷҥӕ'))
console.log(capitalize('🎁❄💊🎸⭐'));
// Title Case
console.log(
'Title Case:',
'foo bar'
.split(/\s+/)
.map(capitalize)
.join(' '),
);
We accept a destructured string as the only parameter [firstLetter, ...rest]
, assigning the first character to the variable firstLetter
and get an array for the rest of the characters (...rest
) bound to the rest
variable. E.g. for the string lorem ipsum
this should look like:
capitalize('lorem ipsum');
// firstLetter = 'l'
// rest = ['o', 'r', 'e', 'm', ' ', 'i', 'p', 's', 'u', 'm'];
Now all we need to do is prepend an uppercased version of the first letter firstLetter.toLocaleUpperCase()
to the rest
array—using the spread operator—and join the resulting array into a string using .join('')
string[0]
works in UTF-16 which has at most 2 bytes (16 bits) per string item, while many unicode characters have 4 bytes (32 bits). Destructuring is ‘unicode’ aware, meaning, it understands which codepoints are 4 bytes and which are 1 or 2 bytes, string[0]
isn’t, so it will take at most 2 bytes at a time, which sometimes is only half the character.
Commented
Mar 29 at 1:25
/*
* As terse as possible, assuming you're using ES version 6+
*/
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());
console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\
This solution might be new and probably the simplest.
function firstUpperCase(input)
{
return input[0].toUpperCase() + input.substr(1);
}
console.log(firstUpperCase("capitalize first letter"));
Functions to include:
/** First Character uppercase */
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/** First Character lowercase */
function uncapitalize(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
Example1 "First Character uppercase":
alert(capitalize("hello world"));
Result: Hello world
Example 2 "First Character lowercase":
alert(uncapitalize("Hello World, today is sunny"));
Result: hello World, today is sunny
s[0].toUpperCase``+s.substr`1`
let s = 'hello there'
console.log( s[0].toUpperCase``+s.substr`1` )
Using prototypes
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
or Using functions
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
There are multiple ways of doing this try some below
var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);
And if you are comfortable with regular expressions, you do things this way:
var upper = lower.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
And you can even take it one step further by using more modern syntax:
const upper = lower.replace(/^\w/, c => c.toUpperCase());
Also this will take care of negative scenarios as mentioned in example like words starting with special characters like !@#$%^&*()}{{[];':",.<>/?
.
Using an arrow function:
const capitalize = string => string[0].toUpperCase() + string.slice(1)
Elegant
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
You can use regex approach :
str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());
try this one line fix
text[0].toUpperCase() + text.substring(1)
function getCapitalizedText(text) {
return text[0].toUpperCase() + text.substring(1)
}
we can call this "getCapitalizedText" any number of times by passing the text.
var capitalizeMe = "string not starting with capital"
Capitalize with substr
var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);
I would just use a regular expression:
myString = ' the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());