DEV Community

Matt Kenefick
Matt Kenefick

Posted on

7 2

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (2)

Collapse
 
harrisgeo88 profile image
Harris Geo πŸ‘¨πŸ»β€πŸ’» β€’

Thank for that script!!! πŸ™Œ

Collapse
 
nightscript profile image
NightScript β€’

What about the title attribute?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs