EN
TypeScript - make first letter of string uppercase
0 points
In this article, we're going to have a look at how to capitalize the first letter of a string in TypeScript.
Quick solution:
Note: presented below example is not universal. Read all article to find better universal solutions.
xxxxxxxxxx
1
function capitalizeTest(text: string): string {
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: string): string => {
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
Presented approaches find the first letter in string and transform it to 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 occurrence with replace
method.
xxxxxxxxxx
1
const expression = /\b\w/;
2
3
function convertSentence(text: string): string {
4
const result = text.replace(expression, function (text) {
5
return text.toUpperCase();
6
});
7
8
return result;
9
}
10
11
// Example:
12
13
const text: string = 'this is some sentence...';
14
const convertedText: string = convertSentence(text);
15
16
console.log(convertedText);
Output:
xxxxxxxxxx
1
This is some sentence...
This section shows how to capitalize first word occurrence with search
method.
xxxxxxxxxx
1
const expression = /\b\w/;
2
3
function convertSentence(text: string): string {
4
const index: number = text.search(expression);
5
6
if (index > -1) {
7
const value: string = text[index];
8
9
const prefix: string = text.substring(0, index);
10
const suffix: string = text.substring(index + 1);
11
12
return prefix + value.toUpperCase() + suffix;
13
}
14
15
return text;
16
}
17
18
// Example:
19
20
const text: string = 'this is some sentence...';
21
const convertedText: string = convertSentence(text);
22
23
console.log(convertedText);
Output:
xxxxxxxxxx
1
This is some sentence...