React Js Detect URLs in Text and Convert to link
React Js Detect URLs in Text and Convert to link:In React.js, detecting URLs in text and converting them into clickable links can be achieved using regular expressions to identify URLs within the text. By leveraging JavaScript's string manipulation functions, you can locate URLs and wrap them in anchor tags (<a>) with appropriate attributes like "href" to create clickable links. Additionally, you can use the "dangerouslySetInnerHTML" prop to render the text with HTML links. This ensures that any URLs in the text are automatically recognized and transformed into clickable links, enhancing user experience when displaying text containing web addresses.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
How can React js be used to detect URLs within text and convert them into clickable links?
This Reactjs code snippet uses a regular expression to detect URLs within a given text. It then splits the text into parts containing both URLs and other text. For each part, if it's a URL, it creates a clickable link element with the URL as the href attribute. If it's regular text, it displays it as-is. This way, it effectively converts URLs in the text into clickable links. The resulting formatted text is rendered in a container, allowing users to interact with the detected URLs.
React Js Detect URLs in Text and Convert to link Example
Copied to Clipboard
x
<script type="text/babel">
function App() {
// Regular expression to match URLs
const text = "Visit Google at https://www.google.com. " +
"Connect with friends on Facebook at https://www.facebook.com. " +
"Network with professionals on LinkedIn at https://www.linkedin.com. " +
"Explore ChatGPT at https://www.chatgpt.com. " +
"Shop for electronics at https://www.amazon.com. " +
"Get the latest fashion trends at https://www.zara.com. " +
"Discover world news at https://www.bbc.com. " +
"Learn about space exploration at https://www.nasa.gov.";
const urlRegex = /(https?:\/\/[^\s]+)/g;
// Split the text into parts containing URLs and other text
const parts = text.split(urlRegex);
// Map the parts to create a mixed array of text and links
const formattedText = parts.map((part, index) => {
if (part.match(urlRegex)) {
// If the part is a URL, convert it to a clickable link
return (
<a key={index} href={part} target="_blank" rel="noopener noreferrer">
{part}
</a>
);
} else {
// If it's regular text, just display it as-is
return <span key={index}>{part}</span>;
}
});
return (
<div className='container'>
<h3>React Js Detect URLs in Text and Convert to link</h3>
{formattedText}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Js Detect URLs in Text and Convert to link
Ad