Reputation: 21
let string = `<img class="img-fluid big-img logo">
<a class="link link-red link-2">link</a>`;
I want to get all the class name by regex not other way
I want to put them inside an array like:
let allClass = ["img-fluid", "big-img", "logo", "link",......];
Upvotes: 2
Views: 1734
Reputation: 6148
Perhaps you could do something like this:
var pattern = /class="([^"]+)"/g;
var classes = [];
[...string.matchAll(pattern)].
forEach(
match => classes = classes.concat( (match[1].split(" ")) )
);
console.log(classes); // ["img-fluid", "big-img", "logo", "link", "link-red", "link-2"]
Effectively here we have a regex that matches class="..."
and captures everything inside of the quotes. Then we run matchAll
with the addition of the spread operator (...
) so that it produces an array we can iterate over with forEach
.
Then we simply loop over the array, split the captured string into an array and merge with the classes
array
Upvotes: 1
Reputation: 21
I have found a solution but I don't know how efficient it is but it works
let regex = /class="(?:([\w+\-])(?:\s|")?){1,}/g;
let collectClass = [];
string.match(regex).forEach(item => { item.replace(`class=`, "").replace(`"`, "").split(" ").forEach(item => collectClass.push(item)) })
allClass = collectClasses.filter((value, index, self) => self.indexOf(value) === index);
Upvotes: 0