'Create objects using last part of a string?

I am creating a react app that takes text input and outputs it in 280 character (tweet-sized) objects, essentially splitting it into one big Twitter thread.

I can't figure out how to split them up into these 280-character objects and keep updating the list of objects (tweets) as I type into the text box?!

Any help would be appreciated.

const [content, setContent] = useState("");
const [tweets, setTweets] = useState([
    { text: "First tweet.", id: 1 },
]);
let remainder = content.length - ~~(content.length / 10) * 10;
  let prevTweetsLength = content.length - remainder;

  const contentHandler = (e) => {
    setContent(e.target.value);
    tweetHandler(content);
    console.log(content);
  };

  const tweetHandler = (c) => {
    tweets[prevTweetsLength / 10] = {
      text: c,
      id: tweets.length + 1,
    };
    if (remainder === 1) {
      setTweets([
        ...tweets,
        {
          text: c.substring((prevTweetsLength)),
          id: Math.random() * 1000,
        },
      ]);
    }
  };```


Solution 1:[1]

First, we can define a function which will split a text into tweets, using slice(start, end) which returns the content between the start position and end position.

function splitIntoTweets(content, tweetLength = 280) {
  const nTweets = content.length / tweetLength;

  const tweets = [];
  for (let i = 0; i < nTweets; i++) {
    tweets.push({
      text: content.slice(i * tweetLength, (i + 1) * tweetLength),
      id: i,
    });
  }
  return tweets;
}

Then, inside your components, you could do:

const [content, setContent] = useState("");
const [tweets, setTweets] = useState([]);

// Every time content changes, we update the list of tweets.
useEffect(() => {
  setTweets(splitIntoTweets(content));
}, [content])

// Rest of your code ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cr4zySheep