You need to enable JavaScript to run this app. JavaScript正则如何捕获顺序、存在性不定的短代码属性对应值
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 23:45:06