Title Case String Manipulation

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert a string into title case using JavaScript. We will use regular expressions to split the string into words and then capitalize the first letter of each word. By the end of this lab, you will have a better understanding of how to manipulate strings in JavaScript and apply this technique to format text in your web applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28663{{"`Title Case String Manipulation`"}} javascript/data_types -.-> lab-28663{{"`Title Case String Manipulation`"}} javascript/arith_ops -.-> lab-28663{{"`Title Case String Manipulation`"}} javascript/comp_ops -.-> lab-28663{{"`Title Case String Manipulation`"}} javascript/higher_funcs -.-> lab-28663{{"`Title Case String Manipulation`"}} end

Function to Convert String to Title Case

To convert a given string to title case, use the following function. It uses String.prototype.match() to break the string into words using an appropriate regular expression. Then it combines them using Array.prototype.map(), Array.prototype.slice(), Array.prototype.join(), and String.prototype.toUpperCase(). This capitalizes the first letter of each word and adds a whitespace between them.

const toTitleCase = (str) =>
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");

Here are some examples of how to use the function:

toTitleCase("some_database_field_name"); // 'Some Database Field Name'
toTitleCase("Some label that needs to be title-cased");
// 'Some Label That Needs To Be Title Cased'
toTitleCase("some-package-name"); // 'Some Package Name'
toTitleCase("some-mixed_string with spaces_underscores-and-hyphens");
// 'Some Mixed String With Spaces Underscores And Hyphens'

Summary

Congratulations! You have completed the Titlecase String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like