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

如何在HTML类名数组中查找仅知前缀的动态特定类名?

解决方案:提取特定格式的类名

这事儿不难搞定,我们可以用正则表达式配合数组方法来精准定位你需要的类名,具体步骤如下:

1. 编写匹配规则的正则

你的目标类名格式是tile-position-[1-4]-[1-4],我们可以写一个严格匹配的正则:

const positionRegex = /^tile-position-[1-4]-[1-4]$/;
  • ^ 和 $ 确保完全匹配整个字符串,避免误判带额外后缀的类名
  • [1-4] 限定数字范围只能是1到4,完美贴合你的格式要求

2. 从数组中筛选匹配项

用数组的find()方法遍历数组,找到第一个符合正则规则的元素(这类类名应该只会有一个):

const matchedClass = arr.find(item => positionRegex.test(item));

相比filter(),find()会在找到第一个匹配项后立即停止遍历,效率更高。

3. 赋值给目标对象

因为对象的属性名带连字符,不能用点语法,所以要用方括号语法赋值:

if (matchedClass) {
  obj["tile-position"] = matchedClass;
}

加个判断是为了防止数组里没有匹配项时,不会给属性赋值undefined。

完整代码示例

var arr = ["tile", "tile-2", "tile-new", "tile-position-1-4", value: "tile tile-2 tile-new tile-position-1-4"];
var obj = { "tile-position": "" };

// 定义匹配正则
const positionRegex = /^tile-position-[1-4]-[1-4]$/;

// 查找匹配的类名
const matchedClass = arr.find(item => positionRegex.test(item));

// 赋值给对象属性
if (matchedClass) {
  obj["tile-position"] = matchedClass;
}

console.log(obj); // 输出: { "tile-position": "tile-position-1-4" }

哪怕数组里的tile-position后缀数字更新,只要符合[1-4]-[1-4]的格式,这个代码都能准确匹配到目标类名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:57:08