Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace regex by regex

I have some text, which contains a markdown link:

var text = 'some text some text [some text](link.md) some text some text';

I want to change that to

var newText = 'some text some text [some text](link.html) some text some text';

basically, changing the .md to .html, but only if it's a valid markdown link. A valid markdown link is []() with text between it.

Currently I have to following regex: /\[.*\]\(.*.md\)/g.

However, how will I perform a regex replace in Javascript (if the regex above matches, replace .md with .html)?

like image 970
Kevin Avatar asked Feb 23 '26 04:02

Kevin


1 Answers

Try this replacement:

var text = '[some text](link.md)';
console.log("Before:\n" + text);
text = text.replace(/(\[[^\]]+\])\(([^\)]+).md\).*/, "$1($2.html)");
console.log("After:\n" + text);
like image 74
Tim Biegeleisen Avatar answered Feb 25 '26 16:02

Tim Biegeleisen