Advertisement
metalni

Untitled

Dec 25th, 2023
1,133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2.  
  3. const detectAndConvertLinks = (text) => {
  4.   // Regular expression to detect URLs
  5.   const urlRegex = /(https?:\/\/[^\s]+)/g;
  6.  
  7.   // Split the text based on URLs
  8.   const parts = text.split(urlRegex);
  9.  
  10.   // Check if each part is a URL or not and create appropriate elements
  11.   return parts.map((part, index) => {
  12.     if (part.match(urlRegex)) {
  13.       return (
  14.         <a key={index} href={part} target="_blank" rel="noopener noreferrer">
  15.           {part}
  16.         </a>
  17.       );
  18.     } else {
  19.       return <span key={index}>{part}</span>;
  20.     }
  21.   });
  22. };
  23.  
  24. export const TextWithLinks = ({ text }) => {
  25.   const textWithLinks = detectAndConvertLinks(text);
  26.  
  27.   return <div>{textWithLinks}</div>;
  28. };
  29.  
  30.  
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement