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('').

function getFirstChar(str) {
  const firstChars = str
    .split(' ')
    .map(word => word[0])
    .join('');

  return firstChars;
}

// 👇️ ABC
console.log(getFirstChar('Alice, Bob, Charlie'));

// 👇️ ONE
console.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

  1. Create a sample string state
  2. Create a function that returns the first char of each word
  3. Call function from function and component

Let’s write code…

import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
  const [sampleString, setSampleString] = useState(
    "Java Script Object Notation"
  );

  const getFirstChar = (str) => {
    const firstChars = str
      .split(" ")
      .map((word) => word[0])
      .join("");

    return firstChars;
  };
  useEffect(() => {
    let short = getFirstChar("Internet of things");
    console.log(short);
  }, []);
  return (
    <div className="App">
      <h1>{getFirstChar(sampleString)}</h1>
    </div>
  );
}

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 👍.