capitalizeEachWord()

Last updated: July 11, 2021

Description

Capitalizes the first letter of every word in a passed string.

const capitalizeEachWord = str =>
  str.replace(/\b[a-z]/g, char => char.toUpperCase());

The function above is using the arrow function syntax that accepts a string as an argument. We then used the JavaScript replace() method that has two parameters, the pattern and the replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. We passed the Regular Expressions as a pattern where it looks for lowercase words matches. Next is we used a function as the replacement which then converts each word matches to uppercase.

Parameters

str - the word or sentence in a string format

Return Values

Returns a string of capitalized first letter of every word in a sentence

Usage

You can pass a word:

capitalizeEachWord('ohayō'); // Result: "Ohayō"

You can pass a sentence:

capitalizeEachWord('hello, luigi!'); // Result: "Hello, Luigi!"

Live Example

Hey, did you find this shortcode useful? I would appreciate if you could share this to your networks.