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

regex replace all matches based on pattern

本文关键字:替换 模式 正则表达式      更新时间:2023-09-26
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来匹配所有引用的文本,并为命令提供一个不带引号的捕获组。然后,您可以在替换字符串中使用"$1"

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

你应该查看 MDN 关于 String.prototype.replace() 的文档,特别是关于将函数指定为参数的部分。

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是正则表达式中第一个捕获组的内容,command1command2(不带引号)。此匿名函数返回的字符串是这些匹配项替换的字符串。

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

找到

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

然后替换

<a href="someurl?cmd=$1">$1</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=$1">$1</a>'; 
var result = str.replace(re, subst);