user
How to get all the links and images URL in a markdown string in JavaScript ?
alphonsio

To extract all the links and image URLs from a Markdown string in JavaScript, you can use regular expressions (regex) to match the syntax patterns for links and images in Markdown. Below is a step-by-step example on how to do this:

  1. Define the Markdown String – This is the input string from which we want to extract links and image URLs.

  2. Set Up Regex Expressions:

    • For Links: Markdown links are typically in the format [link text](URL "optional title").
    • For Images: Markdown images are mostly similar but prefixed with an exclamation mark, like ![alt text](URL "optional title").
  3. Apply Regex to Extract URLs – Use the JavaScript match() method to use the regex and pull out all matches.

  4. Print or Return the Results – Depending on what you require, either log the results to the console or return them from a function.

Here is the regular expression that match the URLs:

const regex = /(?=$$ (!$$ .+? $$$ .+? $|.+?)]$ ((http|https):\/\/[^ $]+)\))/gi

Here is how you could implement this:

const markdown = `Some markdown with [links](https://example.com) and ![images](https://image.com)`;

const regex = /(?=\[(!\[.+? $$$ .+? $|.+?)]$ ((http|https):\/\/[^ $]+)\))/gi;

let links = [...markdown.matchAll(regex)];
console.log (links)

Here is an example online: