Home > front end >  Regex matching classes in className of a React/jsx element
Regex matching classes in className of a React/jsx element

Time:04-29

The following is a snippet of my React component

<div className="grid lg:grid-cols-2 xl:grid-cols-1 lg:gap-x-5">
  <article className={`${index > 0 ? 'border-t lg:border-t-0 xl:border-t border-gray-300/70' : ''} py-8 sm:flex xl:items-center lg:flex-col xl:flex-row`}>
    ...
  </article>
</div>

I need to get all of the classes that are in the component. I was able to match the classes within className="grid lg:grid-cols-2 xl:grid-cols-1 lg:gap-x-5" with the following regex:

/(?<=className=")(.*)(?=")/g

However, I can't figure out how to match the classes for

className={`${index > 0 ? 'border-t lg:border-t-0 xl:border-t border-gray-300/70' : 'text-gray-900'} py-8 sm:flex xl:items-center lg:flex-col xl:flex-row`}

For example, I need to match "border-t lg:border-t-0 xl:border-t border-gray-300/70 text-gray-900 py-8 sm:flex xl:items-center lg:flex-col xl:flex-row" in the above example.

CodePudding user response:

You could try this combination of 3 regex:

Script:

function myFunction() {
  text = "<div className=\"grid lg:grid-cols-2 xl:grid-cols-1 lg:gap-x-5\">\
            <article className={`${index > 0 ? 'border-t lg:border-t-0 xl:border-t border-gray-300/70' : 'text-gray-900'} py-8 sm:flex xl:items-center lg:flex-col xl:flex-row` }\
              ...\
            </article>\
          </div>";

  console.log(text.match(/(?<=\?\s?')([^']*)(?='(\s?:|\s?}))|(?<=}\s?)([^`]*)(?=`\s?})/g).join(' '))
}

Output:

output

Note:

  • You might need to add article className checks before the regex below if you only need the classNames inside an article tag as the regex below might pick up other classes if it in between single quotes ('').
  • Related