Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to detect if String contains url and make url clickable using javascript react js

Hi guys am trying to detect if a string contains url and if yes wrap it using anchor tags and make it click able. but what i have display both the string and the anchor tags.

My code


function urlify(text) {
        var urlRegex = /(https?:\/\/[^\s]+)/g;
        
        return text.replace(urlRegex, function(url) {
            var hyperlink = url;
            if(!hyperlink.match('^https?:\/\/')){
                hyperlink = 'http://' + hyperlink;
            }
          return '<a className="blue" href="' + url + '" rel="noopener" noreferrer>' + url + '</a>'

        })
        // or alternatively
        
      }

Inside my html code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<p>{urlify(text)}</p>

output

first remove anchors before return text.replace – Muneeb Mirza <a className="blue" href="https://onlyfans.com/my/notifications">https://onlyfans.com/my/notifications</a>

Instead of displaying the link with the anchor tags i want to display it as clickable link without the tags.

>Solution :

Assuming the urlify function is working as you expect, the result should be considered an HTML string. Use dangerouslySetInnerHTML to set the inner text of the p tag.

Example:

<p dangerouslySetInnerHTML={{ __html: urlify(text) }} />

As the name suggests, this is potentially a dangerous function, but if you’ve full control over the content and computing the HTML tags that are generated, it’s probably pretty safe.

If you’ve any concern over the content though then I suggest also using DOMPurify to help sanitize the text value before you process it to create the links.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading