Home > OS >  How to split words further into letters in react hooks
How to split words further into letters in react hooks

Time:11-01

I have made a split of the Text. Now I want to split it further into a single letter/character. Further I want to extent the splitting process to a set of array which is inside the content.

Below is my react code:


    import React from "react";
    import "./styles.css";
    import content from "./content";
    
    // Splitting Texts
    const SplitText = React.memo(({ str }) => {
      return (
        <div>
          {str.split(" ").map((item, index) => {
            return <div key={index}>{item}</div>;
          })}
        </div>
      );
    });
    
    // Main App
    export default function App() {
      return (
        <div className="App">
          <h1>
            <SplitText str={"Lucie Bachman"} />
          </h1>
          <h2>
            <SplitText str={"Hey, this is my first post on StackOverflow!"} />
          </h2>
        </div>
      );
    }

CodePudding user response:

When you are using str.split(" ") then you are saying that split the string with separator as " ". It will split the string where the space is there in the string.

But what you want is to split the string with each character, for that you have to split the string with "" as

Live Demo

Codesandbox Demo

<div>
  {str.split("").map((item, index) => {
    return <div key={index}>{item}</div>;
  })}
</div>

Resources

  1. String.prototype.split

CodePudding user response:

you can use the same split API on string to get the letters

console.log("string".split('')); // ['s', 't', 'r', 'i', 'n', 'g']
  • Related