Skip to content
Advertisement

React JS Detect link from text this is my [web](https://www.google.com/)

Do anyone have suggestions to detect link from text Currently in react I am just checking the regex for link using below code:

 urlify(text) {
  var urlRegex = (new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?"));
   return text.replace(urlRegex, function (url) {
   return '<a href="' + url + '" target="_blank">' + url + '</a>';
 });}

  render() {
   let description="this is my [web](http://stackoverflow.com), this is [Google](https://www.google.com/)"
    return (
    <p dangerouslySetInnerHTML={{__html: this.urlify(description)}}></p>
   );}

The output for above code displayed as shown here

But I just wanna display text as This is my web

Advertisement

Answer

If you wanted to continue using dangerouslySetInnerHTML you could use this match/replace to create an anchor…

const text = 'this is my [web](https://www.google.com/)'

const regex = /(.+)[(.+)]((.+))/;

const anchor = text.replace(regex, (match, a, b, c) => {
  const text = `${a[0].toUpperCase()}${a.substring(1)}${b}`;
  return `<a href="${c}">${text}</a>`;
});

console.log(anchor);

…or you could create a bespoke component that maps the array output from the match to some JSX that creates an anchor.

function MarkdownAnchor({ markdown }) {

  const regex = /(.+)[(.+)]((.+))/;
  const match = markdown.match(regex);

  function formatText(str) {
    return `${str[0].toUpperCase()}${str.substring(1)}`
  }

  return (
    <a href={match[3]}>
      {formatText(`${match[1]}${match[2]}`)}
    </a>
  );

}

const markdown = 'this is my [web](https://www.google.com/)';

ReactDOM.render(
  <MarkdownAnchor markdown={markdown} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement