šŸ“• Build AI Agents using LangGraph.js is now out!

React detect URLs in text and convert them to links

Let's see how we can make a React component that takes text, searches for any URLs in the text, and auto-converts these URLs to real HTML links.

For example:

Our component will be named Linkify and below is a usage example:

<Linkify>
    This is my site https://www.js-craft.io/ for other info.
</Linkify>

And this is the code for the implementation of the React component:

const Linkify = ({children})=> {
    const isUrl = word => {
        const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
        return word.match(urlPattern)
    }

    const addMarkup = word => {
        return isUrl(word) ? 
            `<a href="${word}">${word}</a>`:  
            word
    }

    const words = children.split(' ')
    const formatedWords = words.map((w, i) => addMarkup(w))
    const html = formatedWords.join(' ')
    return (<span dangerouslySetInnerHTML={{__html: html}} />)
}

What we do here is to:

  • use the children property to read the text
  • split the given text into words
  • take each word and test it if it's a link, and if so wrap it in a link tag
  • finally pack it all back together and return the result wrapped in a span tag

Here is the full code of the example and the live version on GitHub pages.

You may have noticed that we are using dangerouslySetInnerHTML to set markup content. If we want to add an extra layer of security we can use the DOMPurify package:

import DOMPurify from 'dompurify'

const Linkify = ({children})=> {
    // ... 
    const html = DOMPurify.sanitize(formatedWords.join(' '))
    return (<span dangerouslySetInnerHTML={{__html: html}} />)
}

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


One Reply

  • Your regex
    “`
    const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
    “`
    is not that good. It is really long and does not capture urls that are separated from the next word by a newline char instead of by space char. I found a simpler url regex like
    “`
    /(https?:\/\/[^\s]+)/g (source: https://stackoverflow.com/a/1500501/4997994)
    “`
    to be more effective.

Leave a Reply

Your email address will not be published. Required fields are marked *