Reputation: 413
I want to create a JavaScript function that can look through a string of CSS selectors and select the the elements that are tag names ( body , p , h1 ) from the other selectors such as as IDs and classes ( #test .test1)
An example would be the string: "span#a53195yio1rnin6d2t9 div.first"
would only return span and div leaving the rest
This is what i have so far but it selects everything after ' # ' or ' .'
Upvotes: 2
Views: 37
Reputation: 370689
If your environment supports lookbehind, just lookbehind for a space or the beginning of the line:
const str = "span#a53195yio1rnin6d2t9 div.first";
console.log(
str.match(/(?:^|(?<= ))\w+/gm)
);
Otherwise, if you have to support older browsers, you'll have to iterate through the matches manually - match the beginning of the string or the space, then capture the next word characters in a group, and extract that capturing group:
const str = "span#a53195yio1rnin6d2t9 div.first";
const re = /(?:^| )(\w+)/gm;
const matches = [];
let match;
while (match = re.exec(str)) {
matches.push(match[1]);
}
console.log(matches);
Upvotes: 3