Kevin
Kevin

Reputation: 979

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

Upvotes: 3

Views: 1178

Answers (3)

Michael Chaney
Michael Chaney

Reputation: 3041

You could use a lookbehind:

text.replace(/(?<=\[.*?\])\((.*)\.md\)/, "($1.html)")

It's possible to do it without one by capturing the first part.

Edit:

There are two minor changes to make this work with multiple items in a string. First, add the obvious "g" flag to the regex. But, secondly, make the captured match non-greedy:

text.replace(/(?<=\[.*?\])\((.*?)\.md\)/g, "($1.html)")

As others have pointed out, you can capture the text in the square brackets and also substitute it, but this is a perfect example of using lookbehinds.

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

First, you should use non-greedy mode *? instead of the gready one *. Then you should group the texts and use those groups to generate a new url:

str = str.replace(/\[(.*?)\]\((.*?).md\)/g, function(match, text, href) {
    return "[" + text + "](" + href + ".html)";
});

Shorter using an arrow function:

str = str.replace(/\[(.*?)\]\((.*?).md\)/g, (match, text, href) => 
    "[" + text + "](" + href + ".html)"
);

Example:

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


text = text.replace(/\[(.*?)\]\((.*?).md\)/g, (m, text, href) => "[" + text + "](" + href + ".html)");

console.log(text);

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522646

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

Upvotes: 3

Related Questions