How to Get the First Letter of Each Word in a String in JavaScript
Extracting the first letter of each word in a string is a common task, often used to create acronyms or initials. For example, you might want to convert "HyperText Markup Language" into "HTML".
This guide will teach you two modern and effective methods for solving this problem. You will learn a robust functional approach using split(), map(), and join(), and a more concise alternative using a single regular expression with match().
The Functional Approach (Recommended): split, map, and join
This is a very readable and explicit method that breaks the problem down into a chain of simple steps. It's a great example of the power of functional programming in JavaScript.
The logic:
- Split: Use
split()with a regular expression (/\s+/) to split the string into an array of words, correctly handling any amount of whitespace between them. - Filter: Remove any empty strings that might result from leading or trailing spaces.
- Map: Create a new array containing only the first character of each word.
- Join: Join the array of characters back into a single string.
Problem: we need to get the initials from a full name.
// Problem: How to get "JSD" from this string?
const fullName = 'John Samuel Doe';
Solution: this function chains the methods together for a clean one-liner.
function getInitials(str) {
return str
.split(/\s+/) // Split by one or more spaces
.filter(Boolean) // Remove any empty strings
.map(word => word[0]) // Get the first character of each word
.join(''); // Join the characters back into a string
}
// Example Usage:
console.log(getInitials('John Samuel Doe')); // Output:: "JSD"
// This method is robust and handles messy whitespace correctly.
console.log(getInitials(' leading and multiple spaces ')); // Output:: "lasm"
Why is split(/\s+/) and filter(Boolean) important?
A simple split(' ') is not robust. If your string has multiple spaces between words (e.g., "word1 word2"), split(' ') will create an array with empty strings: ['word1', '', '', 'word2'].
/\s+/splits by one or more whitespace characters, resulting in a cleaner array..filter(Boolean)is a concise trick to remove any remaining "falsy" values (like empty strings) from the array.
The Regular Expression Approach: Using match()
A regular expression offers a more powerful and often more concise way to find all the characters that match a specific pattern. For this task, we can define a pattern that means "the first letter of any word."
We use a regular expression with the match() method to find all characters that occur at a "word boundary."
/\b\w/g: This is our regular expression.\b: Matches a word boundary. This is a zero-width position between a word character and a non-word character (like the start of the string or the space after a word).\w: Matches any word character (letters, numbers, and the underscore).g: The global flag, which tells thematch()method to find all matches, not just the first one.
Solution:
function getInitialsWithRegex(str) {
const matches = str.match(/\b\w/g);
return matches ? matches.join('') : '';
}
// Example Usage:
console.log(getInitialsWithRegex('John Samuel Doe')); // Output:: "JSD"
console.log(getInitialsWithRegex(' leading and multiple spaces ')); // Output:: "lasm"
The match() method directly returns an array of the first letters, which we can then join(). The ternary operator (matches ? ... : '') handles the case where no matches are found.
Conclusion: Which Method Should You Choose?
Both methods are excellent and have their own advantages.
- The functional approach (
split,filter,map,join) is very explicit and readable, especially for developers who are comfortable with chaining array methods. Each step in the process is clearly defined. - The regular expression approach (
match) is more concise and powerful. It is arguably the "right" tool for this specific pattern-matching job, but it may be less intuitive for those who are not as comfortable with regular expressions.
For this particular problem, the regex method is often more direct. However, the functional chain is a more general-purpose text processing pattern that is a valuable tool to know.