EN
JavaScript - make first letter of string uppercase
5
points
In this article, we would like to show you how to capitalize the first letter of a string in JavaScript.
Quick solution:
Note: presented below example is not universal. Read all article to find better universal solutions.
// ONLINE-RUNNER:browser;
function capitalizeTest(text) {
return text && text[0].toUpperCase() + text.slice(1) || text;
}
// Usage examples:
console.log(capitalizeTest('abc'));
console.log(capitalizeTest('this is text'));
Output:
Abc
This is text
ES6 version
// ONLINE-RUNNER:browser;
const capitalizeTest = (text) => {
return text && text[0].toUpperCase() + text.slice(1) || text;
};
// Usage examples:
console.log(capitalizeTest('abc'));
console.log(capitalizeTest('this is text'));
Output:
Abc
This is text
Note: read this article to capitalize text with CSS.
1. Capital letter of first-word examples
Presented approaches find the first letter in string and transform it into upper case. To find the beginning of the first world regular expression is used in the below examples.
1.1. String
replace
method with regular expression example
This section shows how to capitalize first-word occurrences with replace
method.
// ONLINE-RUNNER:browser;
var expression = /\b\w/;
function convertSentence(text) {
var result = text.replace(expression, function(text) {
return text.toUpperCase();
});
return result;
}
// Example:
var text = 'this is some sentence...';
var convertedText = convertSentence(text);
console.log(convertedText);
Output:
This is some sentence...
1.2. String
search
method with regular expression example
This section shows how to capitalize first-word occurrences with search
method.
// ONLINE-RUNNER:browser;
var expression = /\b\w/;
function convertSentence(text) {
var index = text.search(expression);
if(index > -1) {
var value = text[index];
var prefix = text.substring(0, index);
var suffix = text.substring(index + 1);
return prefix + value.toUpperCase() + suffix;
}
return text;
}
// Example:
var text = 'this is some sentence...';
var convertedText = convertSentence(text);
console.log(convertedText);
Output:
This is some sentence...