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:
Define the Markdown String – This is the input string from which we want to extract links and image URLs.
Set Up Regex Expressions:
[link text](URL "optional title")
.![alt text](URL "optional title")
.Apply Regex to Extract URLs – Use the JavaScript match()
method to use the regex and pull out all matches.
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: