Regex: Convert markdown links to HTML anchors

Matt Kenefick
1 min readSep 12, 2020

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

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

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

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

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

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

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);

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;

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

--

--

Matt Kenefick

Chief Product Engineer. Frontend, Backend, Systems, Electronics, 3D Printing, Photography.