如何修改JavaScript的scriptTag.src.match规则以支持任意URL或WP短代码?
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://orhttps://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
srcvalue (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

