简体   繁体   English

JavaScript用正则表达式替换正则表达式

[英]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. 基本上,将.md更改为.html,但前提是它是有效的markdown链接。 A valid markdown link is []() with text between it. 有效的降价链接是[]() ,链接之间有文字。

Currently I have to following regex: /\\[.*\\]\\(.*.md\\)/g . 目前,我必须遵循以下正则表达式:/ /\\[.*\\]\\(.*.md\\)/g .* /\\[.*\\]\\(.*.md\\)/g . /\\[.*\\]\\(.*.md\\)/g . /\\[.*\\]\\(.*.md\\)/g

However, how will I perform a regex replace in Javascript (if the regex above matches, replace .md with .html)? 但是,如何在Javascript中执行正则表达式替换(如果上述正则表达式匹配,则将.md替换为.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. 首先,将明显的“ g”标志添加到正则表达式。 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. 正如其他人指出的那样,您可以将文本捕获在方括号中,也可以将其替换,但这是使用lookbehinds的完美示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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