简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM