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

模拟jQuery元素选择器时,JavaScript split()返回大量空字符串求助

解决字符串拆分HTML选择器的问题

问题原因

你用的正则表达式/.|#/里,.是正则的元字符,会匹配任意单个字符,相当于把原字符串的每一个字符都当作分隔符,拆分后自然全是空字符串。

修复方案

1. 修正拆分正则

把.转义成\.,让它只匹配字面意义的点号,这样分隔符就只有#和.两种:

console.log('button#hello.something'.split(/\.|#/))
// 输出结果: ["button", "hello", "something"]

2. 更精准的提取方式

如果要明确区分标签、ID、类名,用正则匹配比拆分更靠谱:

const selector = 'button#hello.something';
const result = selector.match(/^([a-zA-Z0-9]+)(?:#([a-zA-Z0-9_-]+))?(?:\.([a-zA-Z0-9_-]+))?$/);
if (result) {
  const [_, tagName, id, className] = result;
  console.log('标签:', tagName, 'ID:', id, '类名:', className);
}
// 输出: 标签: button ID: hello 类名: something

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:15:32