匹配 字符串类似'type=""action=""id=""' 需要匹配多个action=""中间的内容。
const str = 'type="" action="edit" id="" action="delete" class="btn" action="create"';
const matchResult = str.match(/action="([^"]*)"/g); // 匹配所有的 action=""
const actions = matchResult.map(match => /action="([^"]*)"/.exec(match)[1]); // 提取 action="" 中的值
console.log(actions);
action="(.*?)"
function getActionValues(str) {
const reg = /action="([^"]*)"/g;
const values = [];
while (reg.test(str)) {
values.push(RegExp.$1);
}
return values;
}
getActionValues('type="" action="edit" id="" action="delete" class="btn" action="create"'); // ['edit', 'delete', 'create']
注意全局匹配标识 g
不要漏了
/(?<=action=").*?(?=")/g
可以使用正则表达式来匹配多个action=""中间的内容。具体正则表达式如下:
/action="([^"]*)"/g
以上正则表达式中,1*表示匹配除了双引号之外的任意字符,()用来捕获匹配的内容。g表示全局匹配。
使用该正则表达式可以将字符串类似'type=""action1="xx"action2="yy"id=""'中所有的action属性值提取出来。以下是一个示例代码:
const str = 'type=""action1="xx"action2="yy"id=""';
const regex = /action="([^"]*)"/g;
let match = null;
const actions = [];
while ((match = regex.exec(str)) !== null) {
actions.push(match[1]);
}
console.log(actions); // ['xx', 'yy']
以上代码中,首先定义了一个字符串str,然后使用上面的正则表达式进行匹配。通过while循环迭代匹配结果,将每个匹配项的第二个值(即括号内的内容)存储在数组actions中。最后输出actions数组即可得到所有action属性对应的值。
- " ↩