0

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>
      );
    }

  • what should be your expected result? Please add in the question itself...[Is this what you want](https://codesandbox.io/s/letterssldr-forked-x573x) – DecPK Nov 01 '21 at 07:05
  • Yes, what did you do sir? actually, my requirement is to split not only a single string but an array of strings. I will be inserting an array like so and inside the codesandbox – Srinivas Murthy. N.A Nov 01 '21 at 07:17
  • Please correct your data first because some of your elements in the `content` array contains an array `[]`. – DecPK Nov 01 '21 at 07:35
  • yes sir.. corrected – Srinivas Murthy. N.A Nov 01 '21 at 07:38
  • Is this what you want [please go to this link and tell me](https://codesandbox.io/s/letterssldr-forked-c04ov?file=/src/App.js) – DecPK Nov 01 '21 at 07:43
  • Yes, that's the result I wanted to continue further. So you just took off the gap inside the split and it gives me the split of individual letter ( -- str.split("").map ) Am I correct Sir? – Srinivas Murthy. N.A Nov 01 '21 at 07:53
  • Added the solution with explanation – DecPK Nov 01 '21 at 08:01

2 Answers2

0

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

console.log("string".split('')); // ['s', 't', 'r', 'i', 'n', 'g']
eamanola
  • 364
  • 1
  • 10
0

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
DecPK
  • 24,537
  • 6
  • 26
  • 42