CSS Class from `class=""` Attribute in JS
Extract the value of a `class="..."` attribute from raw HTML, handling double or single quotes.
Try it in the JS tester →Pattern
regexJS
class\s*=\s*["']([^"']+)["'] (flags: gi)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("class\\s*=\\s*[\"']([^\"']+)[\"']", "gi");
const input = "<div class=\"btn primary\">";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
class\s*=\s* matches the attribute name with optional whitespace around the `=`. ["'] matches either quote style. ([^"']+) captures everything until the matching quote (the class list itself, possibly multiple classes). The closing ["'] matches the same quote style as opened — note this regex doesn't enforce that they MATCH, but in valid HTML they will.
Examples
Input
<div class="btn primary">Matches
class="btn primary"
Input
<span class='card'>Matches
class='card'
Input
<div id="foo">No match
—