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

Time:02-17

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

<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.

CodePudding user response:

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.

  • Related