正则表达式根据模式替换所有匹配项

regex replace all matches based on pattern

var testString = 'Please use "command1" to accept and "command2" to ignore';

我想要实现的只是替换引号之间的字符串,但是在替换时,我需要知道引号内的内容。

替换后应该是这样的:

var result = 'Please use <a href="someurl?cmd=command1">command1</a> to accept and <a href="someurl?cmd=command2">command2</a> to ignore';

我试过类似的方法但没有成功:

            var rePattern = /\"(.*?)\"/gi;
            Text.replace(rePattern, function (match, txt, urlId) {
                return "rendered link for " + match;
            });

您可以使用正则表达式 /"(.+?)"/g 来匹配所有带引号的文本,并为不带引号的命令设置捕获组。然后你可以在替换字符串中使用""

'Please use "command1" to accept and "command2" to ignore'
.replace(/"(.+?)"/g, '<a href="someurl?cmd="></a>');

您可以使用捕获组,然后在替换中引用它。

查找

/\"([^\"]+)\"/gm

然后替换

<a href="someurl?cmd="></a>

https://regex101.com/r/kG3iL4/1

var re = /\"([^\"]+)\"/gm; 
var str = 'Please use "command1" to accept and "command2" to ignore';
var subst = '<a href="someurl?cmd="></a>'; 

var result = str.replace(re, subst);

您应该查看 MDN 关于 String.prototype.replace() 的文档,特别是关于 Specifying a function as a parameter.

的部分
var testString = 'Please use "command1" to accept and "command2" to ignore';
var reg = /"([^"]+)"/g;
var testResult = testString.replace(reg, function (match, p1) {
    return '<a href="someurl?cmd=' + p1 + '">' + p1 + '</a>';
});

replace的第一个参数是正则表达式,第二个参数是匿名函数。该函数发送了四个参数(请参阅 MDN 的文档),但我们只使用前两个:match 是整个匹配的字符串——"command1""command2"——和 p1是正则表达式中第一个捕获组的内容,可以是command1,也可以是command2(不带引号)。这个匿名函数返回的字符串就是那些匹配项被替换的内容。