Home > other >  How can I scan through the list of string array items to identify which part matches regex expressio
How can I scan through the list of string array items to identify which part matches regex expressio

Time:06-17

IMessage is an interface with type string. The app is something like a todo list, but I need it to identify when a URL is typed in and convert it to a clickable link

const [message, setMessage] = useState<string>("");
  const [chat, setChat] = useState<IMessage[]>([]);
  const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)/;

  useEffect(() => {
    chat.forEach(chat => {
      ///function 
    })
    })

here's a bigger piece of code that I have at the moment


const Home: NextPage = () => {
  const [message, setMessage] = useState<string>("");
  const [chat, setChat] = useState<IMessage[]>([]);
  const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)/;

  
  const sendMessage = () => {
    const newMessage = { message: message };
    setChat([...chat, newMessage]);
    setMessage("");
  };

  const inputChanged = (
    event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => setMessage(event.target.value);

  return (
      <div className={styles.container}>
        <Stack
          direction="column"
          spacing={2}
          justifyContent="center"
          alignItems="flex-end"
        >
          {chat.map((message: IMessage) => {
            return (
              <Paper
                style={{
                  backgroundColor: "#6096ba",
                  padding: "5px",
                  borderRadius: "30px",
                }}
                elevation={3}
              >
                <p style={{ maxWidth: "20ch", color: "white" }}>
                  {message.message}
                </p>
              </Paper>
            );
          })}
        </Stack>
    ```

CodePudding user response:

Here you can use it.includes() if I got you right, Then you add whatever you want to do with it. -Another tip: Create your function out of useEffect then just call it inside the effect, you might have a big project then you will find it harder and not useful at all

CodePudding user response:

You don't need to use useEffect for this if you want it to change the rendering to be a link.

Your return would look something like the following. You would choose to either render as plain text or as a link.

return (
  <ol>
    {chat.map((chatMessage) => {
      return chatMessage.match(regex) ? (
        <li>
          <a href={chatMessage}>{chatMessage}</a>
        </li>
      ) : (
        <li>{chatMessage}</li>
      );
    })}
  </ol>
);
  • Related