Home > Software engineering >  how to replace text when a user type text
how to replace text when a user type text

Time:08-28

Hi I'm working on a user mention function now. I have a problem that I can't replace text

If I'm trying to find a user with "@" I can't find a user so that's why I replace text.

  const handleInputComment = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCommentValue({ ...commentValue, comment: e.target.value });

    e.target.value.split(" ").map((text) => {
      if (text.startsWith("@")) {
        text.replace("@", "");
        setMentionSearchValue(text);
        console.log(mentionSearchValue);
        return setIsMentionModalOpen(true);
      }
      return setIsMentionModalOpen(false);
    });
  };

when I see the console.log what I will see like @asdfsdf @sadfasfsaf @asdfjaskfjfkjf

how to replace text? thanks for reading my question.

CodePudding user response:

Do that instead:

  const handleInputComment = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCommentValue({ ...commentValue, comment: e.target.value });

    e.target.value.split(" ").map((text) => {
      if (text.startsWith("@")) {
        setMentionSearchValue(text.replace("@", ""));
        console.log(mentionSearchValue);
        return setIsMentionModalOpen(true);
      }
      return setIsMentionModalOpen(false);
    });
  };

Replace returns the text replaced and it doesn't update the variable. To the text variable was not being updated.

CodePudding user response:

Javascript String Replace function is immutable, hence it won't change the value of text itself, rather, it will return a new value. But the problem with replace is it will replace all the occurances, if you are interested to get rid of the first @ only, you can use slice method. Another issue is, you are printing the value of state right after calling setState i.e. setMentionSearchValue, but setState is an asynchronous function, so you won't see the new value in the console immediately after calling setState. If you want to print it's value after mentionSearchValue gets updated, you need to use useEffect hook.

const handleInputComment = (e: React.ChangeEvent<HTMLInputElement>) => {
  setCommentValue({ ...commentValue, comment: e.target.value });

  e.target.value.split(" ").map((text) => {
    if (text.startsWith("@")) {
      // text.replace("@", "");
      setMentionSearchValue(text.slice(1));
      // console.log(mentionSearchValue);
      return setIsMentionModalOpen(true);
    }
    return setIsMentionModalOpen(false);
  });
};
  • Related