🚀 Ways to Title Case Strings with Javascript
Tags: javascript, webdev, programming, titlecase
Published: 2023-03-16 23:56:50

As part of a recent fix I had to do during work, I needed to title case an input of a group of sentences that would later be used to validate other logic. The problem was that these sentences needed certain considerations when applying the title case.

So, even when this is a specific case for a specific need I saw this as a good opportunity to not only use this article to list a few ways to _title case sentences_ but also to share the solution i ended up using and that could probably be of help to someone.

Let's begin!


## What Title Case means

This just means converting to uppercase the first letter of every word in a sentence while the other ones remain in lowercase. 


## Examples

There are different ways you can find and use to _convert a sentence to title case in Javascript_, here are a few:

### 1. Using replace method and regex
```javascript
function convertToTitleCase(str) {
  if (!str) {
      return ""
  }
  return str.toLowerCase().replace(/\b\w/g, s => s.toUpperCase());
}

console.log(convertToTitleCase('welcome to my article'));
console.log(convertToTitleCase('THE avengers'));
```

The shortest way to accomplish this, we use regex to match only the first letter of each word to then replace it as uppercase.

**_Side note:_** _it's good to normalize the string by converting everything first to lowercase before actually converting to title case._

**Output:**

![Output example 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rnpolcbi1sw85yk984l9.png)


### 2. Using the map() function
```javascript
function convertToTitleCase(str) {
  if (!str) {
      return ""
  }
  
  return str.toLowerCase().split(' ').map(function (word) {
     return word.charAt(0).toUpperCase().concat(word.substr(1));
  }).join(' ');
}

console.log(convertToTitleCase('welcome AGAIN to MY aRticle'));
console.log(convertToTitleCase('THE avengers MOVIe'));
```

We first turn the sentence into an array with ```javascript str.toLowerCase().split(' ')``` then, when using the **map()**, this will do a callback function for each element in the array where with ```javascript (word.charAt(0).toUpperCase() + word.substr(1))```  we transform the element and build a new array from the results.

**Output:**
![Using map()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o04i351cp9v4ndfkv53h.png)


## Applying title case with exceptions

There can be cases where not all words in the sentence would need to be converted, which was the case i run into, here was my solution, which is basically using the map() way but adding the condition to check if the current word was or not eligible for title case.

```javascript
const exceptions = ['of', 'the', 'and'];

function convertToTitleCase(str) {
  if (!str) {
      return ""
  }
  
  return str.toLowerCase().split(' ').map((word, i) => {
            return exceptions.includes(word) && i != 0 ? word : word.charAt(0).toUpperCase().concat(word.substr(1));
		}).join(' ');
} 

console.log(convertToTitleCase('lord OF the rings'));	
console.log(convertToTitleCase('people AND people'));	
console.log(convertToTitleCase('someTHING ABOUT THE article'));
```

**Output:**
![my case](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8d0cddf66ikpl2uq0k8d.png)



## Conclusion
There are many options out there we could use to convert sentences to title case, we just need to go with the one that works best for our needs.

Also, keep in mind that there could be edge cases where converting to title case can be used or adapted to, it will depend on what exactly needs to be accomplished with it and how it's going to be used since there can be scenarios where it will could probably be impossible to always be correct when the input has been transformed.


**_Happy learning and thank you for reading!_**

_If this article was helpful to you, don't forget to hit that ❤️ button and support me with a follow, i will keep posting more content about tech, programming, career development and more! :)_