JavaScript正则如何捕获顺序、存在性不定的短代码属性对应值
JavaScript 匹配短代码正则方案
最终正则表达式
支持属性任意顺序、可选属性、标签内任意空格,适配 ES2018+ 环境:
const responsiveImageRegex = /{{<\s*shortcodes\/responsive-image\s*(?:.*?image_path=(["'][^"']*["']))?(?:.*?caption=(["'][^"']*["']))?(?:.*?alt=(["'][^"']*["']))?.*?>}}/s
如果需要兼容更低版本JS环境,去掉s修饰符,将所有.*?替换为[\s\S]*?即可:
const responsiveImageRegex = /{{<\s*shortcodes\/responsive-image\s*(?:[\s\S]*?image_path=(["'][^"']*["']))?(?:[\s\S]*?caption=(["'][^"']*["']))?(?:[\s\S]*?alt=(["'][^"']*["']))?[\s\S]*?>}}/
效果说明
三个捕获组对应关系如下:
$1:image_path属性值,属性不存在时为undefined,可通过?? null转为你需要的null值$2:caption属性值,属性不存在时为undefined$3:alt属性值,属性不存在时为undefined
测试代码
const testCases = [ '{{< shortcodes/responsive-image image_path="/image.jpg" caption="A caption" alt="Alt text" >}}', '{{< shortcodes/responsive-image caption="A caption" alt="Alt text" image_path="/image.jpg" >}}', '{{< shortcodes/responsive-image image_path="/image.jpg" alt="Alt text" >}}', '{{< shortcodes/responsive-image image_path="/image.jpg" caption="A caption" >}}', '{{< shortcodes/responsive-image image_path="/image.jpg" >}}', '{{< shortcodes/responsive-image >}}' ] testCases.forEach(item => { const [, $1, $2, $3] = item.match(responsiveImageRegex) ?? [] console.log(`$1: ${$1 ?? null} $2: ${$2 ?? null} $3: ${$3 ?? null}`) })
运行上述代码输出结果和你给出的期望完全一致。
内容的提问来源于stack exchange,提问作者AJP
相关产品推荐
相关产品推荐

