DEV Community

Matt Kenefick
Matt Kenefick

Posted on

Regex: Convert markdown links to HTML anchors

Your typical Markdown link is in a bracket/parenthesis format:

[I'm an inline-style link](https://www.google.com)
Enter fullscreen mode Exit fullscreen mode

…but you may want to convert it to an HTML format:

<a href="https://www.google.com">I'm an inline-style link</a>
Enter fullscreen mode Exit fullscreen mode

To convert that using Regular Expressions, you can use an expression:

/\[([^\]]+)\]\(([^\)]+)\)/
Enter fullscreen mode Exit fullscreen mode

For Javascript (try it):

var markdown = "[I'm an inline-style link](https://www.google.com)";
var html = markdown.replace(/\[([^\]]+)\]\(([^\)]+)\)/, '<a href="$2">$1</a>');
alert(html);
Enter fullscreen mode Exit fullscreen mode

For PHP (try it):

<?php
$markdown = "[I'm an inline-style link](https://www.google.com)";
$html = preg_replace('/\[([^\]]+)\]\(([^\)]+)\)/', '<a href="\2">\1</a>', $markdown);
echo $html;
Enter fullscreen mode Exit fullscreen mode

Breakdown

/  \[([^\]]+)\]\(([^\)]+)\)  /

\[([^\]]+)\]
   \[    Look for a literal left bracket, by escaping it
   (     Start a capture group to retrieve the contents
  [^\]]+ Repeatedly find a character that isn't a closing bracket
   )     Close the capture group
   \]    Look for a literal right bracket, by escaping it

\(([^\)]+)\)
   \(    Look for a literal left parenthesis, by escaping it
   (     Start a capture group to retrieve the contents
  [^\)]+ Repeatedly find something that isn't a right parenthesis
   )     Close the capture group
   \)    Look for a literal right parenthesis, by escaping it
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
harrisgeo88 profile image
Harris Geo 👨🏻‍💻

Thank for that script!!! 🙌

Collapse
 
nightscript profile image
NightScript

What about the title attribute?