Hi 👋,
Welcome To Infinitbility! ❤️
To get first letter of each word in react js, just use string.split(' ').map(i => i.charAt(0))
it will split your string with space ( you can put any other separator also ), and help of map()
and charAt()
method it will return array of first letter of each word.
Or instead of array you want as a string of first letter of each word just use join('')
method after map()
like this string.split(' ').map(i => i.charAt(0)).join('')
.
1function getFirstChar(str) {2 const firstChars = str3 .split(' ')4 .map(word => word[0])5 .join('');67 return firstChars;8}910// 👇️ ABC11console.log(getFirstChar('Alice, Bob, Charlie'));1213// 👇️ ONE14console.log(getFirstChar('Oscar Noah Emily.'));
Today, I’m going to show you How do I get the first letter of each word in a string in to react js, as above mentioned here, I’m going to use the Object.keys()
method with length to check empty objects.
Let’s start today’s tutorial how do you get the first letter of every word in a string in react js?
In this example, we will do
- Create a sample string state
- Create a function that returns the first char of each word
- Call function from function and component
Let’s write code…
1import React, { useState, useEffect } from "react";2import "./styles.css";3export default function App() {4 const [sampleString, setSampleString] = useState(5 "Java Script Object Notation"6 );78 const getFirstChar = (str) => {9 const firstChars = str10 .split(" ")11 .map((word) => word[0])12 .join("");1314 return firstChars;15 };16 useEffect(() => {17 let short = getFirstChar("Internet of things");18 console.log(short);19 }, []);20 return (21 <div className="App">22 <h1>{getFirstChar(sampleString)}</h1>23 </div>24 );25}
As mentioned above, we are taken the example of a sample string state, created a function that returns the first char of each word, using a function, and printed output on a screen.
Let’s check the output.
I hope it’s help you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.