Capitalize in JavaScript/TypeScript

Posted by


In JavaScript/TypeScript, capitalizing a string can be done easily using a few different methods. The most commonly used method is to use a combination of methods, such as toUpperCase(), toLowerCase(), and substring(), to achieve the desired result. In this tutorial, we will explore different ways to capitalize a string in JavaScript/TypeScript.

  1. Using the toUpperCase() and toLowerCase() methods:

One way to capitalize a string in JavaScript/TypeScript is to convert the entire string to lowercase first, and then capitalize the first letter. Here’s an example code snippet that demonstrates this method:

function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

console.log(capitalize("hello")); // Output: Hello

In this code snippet, we first use the charAt(0) method to extract the first letter of the string, then we use the toUpperCase() method to capitalize the first letter. Next, we use the slice(1) method to extract the rest of the string (starting from the second character), and finally use the toLowerCase() method to convert the rest of the string to lowercase.

  1. Using the substring() method:

Another way to capitalize a string in JavaScript/TypeScript is to use the substring() method to extract the first letter of the string, capitalize it, and then concatenate it with the rest of the string. Here’s an example code snippet that demonstrates this method:

function capitalize(str: string): string {
  return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}

console.log(capitalize("world")); // Output: World

In this code snippet, we first use the substring(0, 1) method to extract the first letter of the string, then we use the toUpperCase() method to capitalize the first letter. Next, we use the substring(1) method to extract the rest of the string (starting from the second character).

  1. Using regular expressions:

Another way to capitalize a string in JavaScript/TypeScript is to use regular expressions to replace the first letter of the string with its uppercase version. Here’s an example code snippet that demonstrates this method:

function capitalize(str: string): string {
  return str.replace(/^./, str[0].toUpperCase());
}

console.log(capitalize("example")); // Output: Example

In this code snippet, we use the replace() method along with a regular expression /^./ to match the first character of the string. We then use the toUpperCase() method to capitalize the matched character.

These are just a few ways to capitalize a string in JavaScript/TypeScript. Depending on your specific use case, you may choose one method over another. Experiment with these methods and see which one works best for your particular scenario. Happy coding!

0 0 votes
Article Rating

Leave a Reply

17 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@webstar5550
5 days ago

Lodash можно использовать 😂

@Ырфь
5 days ago

регекспом удобнее наверное .replace(/(?:^|s)S/g, f => f.toUpperCase()). всё это детский сад, ребят…

@Arkady_Petrov-ua
5 days ago

А зачем это делать средствами js?

@Vandomas
5 days ago

что за плагин вывода консоль лога?

@Ilya-gv6kb
5 days ago

Так можно просто обратится к CSS свойствам в этой функции
Не пойму какие выгоды так программить

@chimchimsterschannel161
5 days ago

John Doe неопознанный умерший в США😂

@LHLetale
5 days ago

Зачем вообще сплитать и мапить все?
str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();

что-то типо такого? и так буде же работать

@xanteI
5 days ago

Так есть же css свойство text-transform: capitalize, зачем под это отдельную функцию делать?

@valer0chka189
5 days ago

А используя регекс не будет эффективнее?

@myrichstory
5 days ago

Перед сплитом желательно ещё удалить двойные и другие лишние пробелы. Ну или фильтром на пустую строку сразу после сплита.

@rea1m_
5 days ago

Можно за O(N) управиться

@HalauLilau
5 days ago

Зачем map

@Bad_ruby
5 days ago

Сказать, что я в шоке, это просто ничего не сказать … я в шоке 😂😂😂
Пачиму я ничиго ни панимаю !!!!!

@cheesecheesson9842
5 days ago

str.replace(str[0], str[0].toUpperCase())

@cheesecheesson9842
5 days ago

str[0].toUpperCase() + str.slice(1, str.length)

@waldo_
5 days ago

Посмотрел недавно выступление Владимира Агафонкина (отца Leaflet), про алгоритмическое мышление. Данный подход из цепочки функций очень медленный (каждая функция создает новый массив, то есть тратит лишнюю память и время), можно оптимизировать!)
А еще можно вынести эту функцию в прототипы строки, тогда ничем не отличишь от встроенных toLowerCase и toUpperCase😊

@faxtel7771
5 days ago

А что за IDE в которой сразу виден результат? Можете подсказать?

17
0
Would love your thoughts, please comment.x
()
x