Regex filter returning object Object instead of element

I am receiving data from an external api that has urls throughout it,
i.e.

sampleText = Ethereum’s original token distribution event, managed by the [Ethereum Foundation](https://messari.io/asset/ethereum)

I want to turn the urls into links using:

 const turnIntoLink =(text)=>{
    const urlFilter = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
    return text.replace(urlFilter, (url)=>{
      return '<a href="' + url + '">' + url + "</a>";
    })
  }
turnIntoLink(sampleText)

when i use the above code it properly reads the urls but returns

... managed by the [Ethereum Foundation](<a href="https://messari.io/asset/ethereum">https://messari.io/asset/ethereum</a>) 

when I change turnIntoLink to this

 const turnIntoLink =(text)=>{
    const urlFilter = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
    return text.replace(urlFilter, (url)=>{
      return <a href={url}>${url}</a>;
    })
  }

it returns

... managed by the [Ethereum Foundation]([object Object])

How can i get it to return an actual a element?

10 thoughts on “Regex filter returning object Object instead of element”

  1. You can use

    const turnIntoLink = (text) => {
        const urlFilter = /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi;
        return text.replace(urlFilter, '<a href="$2">$1</a>');
    }
    

    See the regex demo. Details:

    • \[ – a [ char
    • ([^\][]*) – Group 1: any zero or more chars other than ] and [
    • ]\(]( string
    • ((?:https?|ftps?|file):\/\/[^()]*) – Group 2: http, https, ftp, ftps, file and then a :// substring and then any zero or more chars other than ( and )
    • \) – a ) char.

    See the JavaScript demo:

    const turnIntoLink = (text) => {
        const urlFilter = /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi;
        return text.replace(urlFilter, '<a href="$2">$1</a>');
    }
    
    console.log( turnIntoLink("Ethereum’s original token distribution event, managed by the [Ethereum Foundation](https://messari.io/asset/ethereum)") );
    Reply

Leave a Comment