Find CSS Classes in HTML Using Regular Expressions
Cleaning up old CSS can be a messy chore. I’ve decided to finally make it just a little simpler. The editor I’m using is Visual Studio 2010. The primary issue I faced was finding where a given CSS class was being applied in the html.
Usually it’s as simple as doing a search for the class name. Let’s look at a couple of examples. Let’s say that the class name is “button” or “text”; not easy. “button” will find <button ..> and “text” will find <textarea …>, etc. Next I tried using “Match whole word” option in the “Find and Replace” dialog. This helped narrow down some results, but not enough and not for all search terms. Is there anything that’s bulletproof?
Regular expressions, I thought. VS has a Regular expression search option.
Press Ctrl-F to bring up the “Find and Replace” dialog. Click the “Use” checkbox and select “Regular expressions”
What might that look like? I’m not a regex expert by any means, but I read enough of a regex book to figure this out. If you’d like to better understand the regex code, I may later write that explanation. I don’t yet understand the usage of < and >.
Before I get into my process, let’s take a look at the final result so we know where we’re headed. The class we are looking for is “className”.
(class=['|"][a-zA-Z ^"']*<className>)|(\.className *[{|,])|(addClass\(['|"]className['|"]\))
Ok, how did I get to this? I started out with this…
class="className and class="[a-zA-Z ^"]*<className>"
The first is to catch the class name at the beginning of the class list; the second is for the end.
Next I wanted to combine these into a single statement and allow single quotes ( ‘ ) as well as double quotes ( “ ).
class=['|"][a-zA-Z ^"']*<className>
That’s better. It finds class names anywhere in the class list. What about in the CSS itself?
\.className *[{|,]
Combined looks like
(class=['|"][a-zA-Z ^"']*<className>)|(\.className *[{|,])
This may be enough for most people doing HTML and CSS. Next is adding references to jQuery dynamically adding the class. Again, allowing for usage of single or double quotes.
addClass\(['|"]className['|"]\)
All together it looks like this
(class=['|"][a-zA-Z ^"']*<className>)|(\.className *[{|,])|(addClass\(['|"]className['|"]\))
I will continue to update this until I get it just right and understand all of the code. As always, feel free to comment, add to what I wrote, or critique the code.
– Ryan D Kyle
