如何使自定义shortcode仅在包含方括号时生效?
让自定义短代码仅在方括号包裹时生效
当前你的shortcode函数会解析无方括号的文本(比如itemText num="1" title="This is a title"),但我们需要它只响应被方括号包裹的合法格式(比如[itemText num="1" title="This is a title"])。
修改方案
核心是在代码中加入方括号格式校验,只有符合[shortcode ...]结构的内容才会被处理,具体改动如下:
- 更新
shortCode函数:- 先判断输入文本是否以
[开头且以]结尾,不符合直接返回false - 符合格式的话,先去掉首尾的方括号,再执行原有的参数解析逻辑
- 先判断输入文本是否以
- 优化调用逻辑:
- 在遍历元素时,先校验文本是否是方括号包裹的
itemtext短代码,避免无效处理
- 在遍历元素时,先校验文本是否是方括号包裹的
修改后的完整代码
JavaScript代码
function shortCode(a, b, c) { // 校验是否为方括号包裹的格式 if (!/^\[.*\]$/.test(a)) { return false; } // 移除首尾方括号 const cleanContent = a.slice(1, -1); var split = cleanContent.split(" "), regex = /(?<=")\w.*?(?=")/g; for (var i = 0; i < split.length; i++) { var pair = split[i].split("="); if (pair[0].trim() == b) { c = pair[1]; if (c.match(regex) != null) { return String(c.match(regex)).trim() } else { return false } } } return false } $(".test span").each(function () { var $this = $(this), text = $this.html().trim(), lowerText = text.toLowerCase(); // 仅处理方括号包裹的itemtext短代码 if (lowerText.startsWith("[itemtext") && lowerText.endsWith("]")) { var num = shortCode(text, "num"), title = shortCode(text, "title"); $this.text(num + " " + title); // 预期输出: 1 This is a title } });
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="test"> <!-- 有效格式:会被解析 --> <span>[itemText num="1" title="This is a title"]</span> <!-- 无效格式:不会被解析 --> <span>itemText num="2" title="This won't be processed"</span> </div>
关键改动说明
- 用正则
/^\[.*\]$/确保输入文本被完整的方括号包裹 - 通过
slice(1, -1)移除方括号,不影响后续参数解析逻辑 - 在调用时增加
startsWith和endsWith判断,提前过滤无效内容,提升效率
内容的提问来源于stack exchange,提问作者Priyo Guideline
相关产品推荐
相关产品推荐

