正则表达式根据模式替换所有匹配项
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
来匹配所有引用的文本,并为命令提供一个不带引号的捕获组。然后,您可以在替换字符串中使用"$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
是正则表达式中第一个捕获组的内容,command1
或command2
(不带引号)。此匿名函数返回的字符串是这些匹配项替换的字符串。
可以使用捕获组,然后在替换中引用它。
找到
/'"([^'"]+)'"/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);
相关文章:
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 替换模式忽略模式中的字符
- 正则表达式根据模式替换所有匹配项
- RegExp替换不替换为模式
- 如何在 JavaScript 中替换遵循模式的所有单词
- Javascript:模式HREF需要替换
- 如何使用不可变对象替换观察者模式
- 替换“if else”语句的模式
- Jquery:在一个字符串中查找所有实例模式,提示用户替换模式的所有实例,然后进行替换
- 将弹出窗口替换为引导模式
- 哪种模式在 gsub 中使用!将有序列表 (li 标记) HTML 字符串替换为订单号
- 通过单击替换引导模式的主体
- 将字符串中的正则表达式模式替换为依赖于匹配项的替换字符串
- 根据Javascript中的模式替换单词
- Regex捕获并替换html标记外的文本模式
- 在JavaScript中全局替换数组模式中的字符串
- regexp来修改带有替换模式的匹配项
- IE7|8中使用特殊替换模式替换字符串的奇怪行为
- jQuery中的RegEx在SharePoint的多行文本字段列表视图中用链接替换模式
- 如何返回regex匹配子集(可能通过替换模式,但不进行替换)