2
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",......];
happyCode
  • 21
  • 2
  • 1
    [Don't use regex to parse markup/html](https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not) – Andreas Apr 13 '21 at 06:29
  • 1
    we expect you have done some research and write some code. – Sfili_81 Apr 13 '21 at 06:30
  • 1
    `DOMParser` + `.classList` – Andreas Apr 13 '21 at 06:32
  • 1
    I tried it with regex but my pattern was not working as I expected. I know how to do it by using dom function but I want to do this as a string and want to get class name by regex – happyCode Apr 13 '21 at 06:36
  • duplicate of https://stackoverflow.com/questions/42152454/javascript-regex-get-class-name – Kareem Kamal Apr 13 '21 at 06:52
  • Does this answer your question? [Javascript RegEx get class name](https://stackoverflow.com/questions/42152454/javascript-regex-get-class-name) – Kareem Kamal Apr 13 '21 at 06:52

2 Answers2

1

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

Steven
  • 5,978
  • 2
  • 14
  • 28
0

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);
happyCode
  • 21
  • 2