JS正则可匹配title、caption标签,新增多标签后匹配失效如何解决?
解决方案
原正则为硬编码匹配固定两个键的结构,新增键后无法适配,只需改为全局匹配所有符合键名=(值)格式的内容,再提取捕获分组即可,完整代码如下:
$(".sidebar").each(function() { const e = $(this); const t = e.find(".widget").text(); if (t) { // 全局匹配所有目标结构,提取括号内的内容 const matchResult = Array.from(t.matchAll(/\w+=\(([^)]*)\)/g), item => item[1]); // 空格拼接得到要求的输出格式 const output = matchResult.join(' '); alert(output); } });
完整测试用HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='sidebar'> <div class='widget'>title=(example1) caption=(example2) button=(example3) price=(example4) off=(example5)</div> </div>
如果需要兼容ES2020以下的低版本JS环境,可以替换为exec循环写法实现相同效果:
$(".sidebar").each(function() { const e = $(this); const t = e.find(".widget").text(); if (t) { const reg = /\w+=\(([^)]*)\)/g; const matchResult = []; let match; while((match = reg.exec(t)) !== null) { matchResult.push(match[1]); } const output = matchResult.join(' '); alert(output); } });
内容的提问来源于stack exchange,提问作者Dasy
相关产品推荐
相关产品推荐

