3

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

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I was writing and answer using $1 and $3 but I quit in shame after seeing this lovely example clarity.
0

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.

3 Comments

This seems to only work on the last instance in a string like '[some text](link.md) [some other text](anotherlink.md) '
This code doesn't appear to be working. I seem to recall that you can't use a loosbehind for a replacement (I also thought of doing this here).
It works in the latest version of Chrome. They added lookbehind support recently to Javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.