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.
xxxxxxxxxx
1
function capitalizeTest(text) {
2
return text && text[0].toUpperCase() + text.slice(1) || text;
3
}
4
5
// Usage examples:
6
7
console.log(capitalizeTest('abc'));
8
console.log(capitalizeTest('this is text'));
Output:
xxxxxxxxxx
1
Abc
2
This is text
xxxxxxxxxx
1
const capitalizeTest = (text) => {
2
return text && text[0].toUpperCase() + text.slice(1) || text;
3
};
4
5
// Usage examples:
6
7
console.log(capitalizeTest('abc'));
8
console.log(capitalizeTest('this is text'));
Output:
xxxxxxxxxx
1
Abc
2
This is text
Note: read this article to capitalize text with CSS.
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.
This section shows how to capitalize first-word occurrences with replace
method.
xxxxxxxxxx
1
var expression = /\b\w/;
2
3
function convertSentence(text) {
4
var result = text.replace(expression, function(text) {
5
return text.toUpperCase();
6
});
7
8
return result;
9
}
10
11
// Example:
12
13
var text = 'this is some sentence...';
14
var convertedText = convertSentence(text);
15
16
console.log(convertedText);
Output:
xxxxxxxxxx
1
This is some sentence...
This section shows how to capitalize first-word occurrences with search
method.
xxxxxxxxxx
1
var expression = /\b\w/;
2
3
function convertSentence(text) {
4
var index = text.search(expression);
5
6
if(index > -1) {
7
var value = text[index];
8
9
var prefix = text.substring(0, index);
10
var suffix = text.substring(index + 1);
11
12
return prefix + value.toUpperCase() + suffix;
13
}
14
15
return text;
16
}
17
18
// Example:
19
20
var text = 'this is some sentence...';
21
var convertedText = convertSentence(text);
22
23
console.log(convertedText);
Output:
xxxxxxxxxx
1
This is some sentence...