You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改JavaScript的scriptTag.src.match规则以支持任意URL或WP短代码?

Solution: Adjust JavaScript Match for Any URL or WordPress Shortcode

Got it, let's break down how to tweak your code to meet both of your needs—matching any URL, and matching your WordPress shortcodes.

1. Matching Any URL

To target any valid URL in scriptTag.src, we can use a flexible regex that covers most common URL formats (including http/https, relative paths, domains with query params, etc.). Here's a reliable pattern:

// Regex to match any standard URL
const anyUrlRegex = /(https?:\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/;

This regex handles:

  • Optional http:// or https:// prefixes
  • Domain names with letters, numbers, and hyphens
  • Paths, query parameters, and URL fragments

2. Matching WordPress Shortcodes

Your example shows a shortcode like [my wp shortcode]—so we need to match text wrapped in square brackets. A basic regex for this works for most WP shortcode formats:

// Regex to match any text wrapped in [] (standard WP shortcode structure)
const wpShortcodeRegex = /\[.*?\]/;

If your shortcodes follow a specific pattern (e.g., always start with my-), you can make it more precise to avoid false matches:

// Regex for shortcodes starting with "my-"
const specificWpShortcodeRegex = /\[my-.+?\]/;

3. Combine Both Checks

To match either any URL or your WordPress shortcode, combine the two regex patterns with a pipe (|):

// Combined regex: match any URL OR any WP shortcode
const combinedRegex = /(https?:\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?|\[.*?\]/;

// Use it in your condition
if (scriptTag.src.match(combinedRegex)) {
  // Your logic here
}

Quick Notes:

  • If you want to ensure the match covers the entire src value (not just a partial snippet), add ^ at the start and $ at the end of the regex:
    const exactMatchRegex = /^((https?:\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?|\[.*?\])$/;
    
  • The .*? in the shortcode regex is a non-greedy match—it stops at the first closing ], which avoids issues with accidental nested brackets (though WP shortcodes rarely use nesting).

内容的提问来源于stack exchange,提问作者user9860866

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:41:07