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

如何拆分htmlElement#idName.className格式的字符串?附示例

Split CSS-like Selector String into Individual Parts

Hey there! I've got a couple of straightforward solutions to split your selector string into the exact array format you need. Let's dive right in.

Method 1: Using split() with a Positive Lookahead Regex

This is probably the cleanest approach. We can use a regex that matches the position right before a # or . character (without consuming the character itself), then split the string at those positions:

const selectorStr = 'header#top.header.header--show-offset';
const splitParts = selectorStr.split(/(?=#|\.)/);

console.log(splitParts);
// Output: [ 'header', '#top', '.header', '.header--show-offset' ]

How this works:

  • The regex (?=#|\.) is a positive lookahead — it checks if the next character is either # or ., but doesn't include that character in the split boundary.
  • When we split the string at these positions, we end up with exactly the individual selector segments you want, no extra filtering needed.

Method 2: Using match() with a Capture Regex

If you prefer using match() instead, we can write a regex that captures each valid selector segment directly:

const selectorStr = 'header#top.header.header--show-offset';
const splitParts = selectorStr.match(/([^#.]+)|(#[\w-]+)|(\.[\w-]+)/g).filter(Boolean);

console.log(splitParts);
// Output: [ 'header', '#top', '.header', '.header--show-offset' ]

How this works:

  • ([^#.]+): Captures the initial element name (one or more characters that aren't # or .)
  • (#[\w-]+): Captures ID selectors (starts with #, followed by letters, numbers, underscores, or hyphens)
  • (\.[\w-]+): Captures class selectors (starts with ., followed by valid class characters)
  • The g flag makes the regex match globally across the string, and filter(Boolean) cleans up any accidental empty matches (though in this case, it's mostly a safety net).

Both methods will give you the exact array output you're looking for. The split() approach is more concise, but the match() method might feel more explicit if you want to see exactly what's being captured.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:35:10