1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
In this blogpost, we’ll see how to get the first characters from all the words in a Javascript string, using: split, map, and join; regular expressions; reduce; and array destructuring. We’ll also cover some common errors and a practice problem.
.split()
, .map()
, and .join()
This classic function trio can be used to:
const str = "hello world";
const result = str.split(' ')
.map(word => {
console.log(word.charAt(0)); // Actual Output: h, w
return word.charAt(0);
})
.join('');
console.log(result); // Actual Output: hw
Explanation:
split(' ')
: Splits the string into an array of words using a space as the delimiter.map(word => word.charAt(0))
: Maps each word to its first letter using the charAt(0)
method.join('')
: Joins the array of first letters back into a single string.For regex enthusiasts, we can get all words using regex pattern /b/w
, and then like previous approach we map every word to initials, and then join the initials.
const str = "hello world";
const result = str.match(/w/g).map(letter => {
console.log(letter); // Actual Output: h, w
return letter;
}).join('');
console.log(result); // Actual Output: hw
Regex symbols Explanation:
/
: Denotes the beginning of the regular expression.\b
: Matches a word boundary.\w
: Matches any word character (alphanumeric + underscore).g
: Global flag for matching all occurrences in the string.\b\w
ensures we capture the first letter of each word..reduce()
This functional approach involves reducing the array of words to accumulate their first letters:
const str = "hello world";
const result = str.split(' ')
.reduce((acc, word) => {
console.log(acc + word[0]); // Actual Output: h, hw
return acc + word[0];
}, '');
console.log(result); // Actual Output: hw
Explanation:
split(' ')
: Splits the string into an array of words.reduce((acc, word) => acc + word[0], '')
: Iterates over the array, accumulating the first letter of each word.Unpack those letters elegantly using array destructuring:
const str = "hello world";
const result = str.split(' ')
.map(([firstLetter]) => {
console.log(firstLetter); // Actual Output: h, w
return firstLetter;
})
.join('');
console.log(result); // Actual Output: hw
([firstLetter])
: Destructures the array to directly access the first letter.To include punctuation following a word (e.g., “Hello!”), modify the regular expression or adjust the handling accordingly.
const str = "hello, world!";
const result = str.match(/w|W/g).map(letter => {
console.log(letter); // Actual Output: h, e, l, l, o, ,, w, o, r, l, d, !
return letter;
}).join('');
console.log(result); // Actual Output: helloworld!
\W
: Matches any non-word character, including punctuation.Ensure your code accounts for empty input strings to prevent unexpected results. In all methods, an empty string would produce an empty result.
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Implement a function that upgrades each element in an array by squaring it
Problem (JavaScript)
/**
* Generates initials from a full name.
*
* @param {string} fullName - The full name to extract initials from.
* @returns {string} - The generated initials.
*/
function generateInitials(fullName) {
// > > > 👉 Write code here 👈 < < <
}
// Example:
const initials = generateInitials("john doe");
console.log(initials); // Output: "JD"
Please attempt before seeing the Answer:
function generateInitials(fullName) {
if (!fullName || typeof fullName !== 'string') {
return 'Invalid input';
}
// Split the full name into an array of names
const names = fullName.trim().split(/s+/);
let initials = '';
for (const name of names) {
if (name.length > 0) {
// Capitalize and append the first letter of each name
initials += name[0].toUpperCase();
}
}
return initials;
}
Explanation:
split(/\\s+/)
: Splits the trimmed full name into an array of names, considering one or more consecutive whitespaces as the delimiter.Why do programmers prefer dark mode? Because light attracts bugs. 😉
Happy coding, and may your code be as clean as your favorite editor theme! 🚀
Feel free to reach out!