如何拆分htmlElement#idName.className格式的字符串?附示例
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
gflag makes the regex match globally across the string, andfilter(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

