Regular Expressions 101

Community Patterns

Community Library Entry

2

Regular Expression
ECMAScript (JavaScript)

/
(?:(\bclass)(?:[:]([_a-zA-Z0-9-]+))?\s*[=]?(?:[{}]{0,}['"\s]*\b(.+)?\b["'\s]*[{}]*)?)|(?:\B([@]apply)\s+([_a-zA-Z0-9-\s\:\/]*)[;]?)
/
gm

Description

SvelteComponent Class Directive Matching

Also supports TailwindCSS-style @apply directive for the class value.

class:directive={boolean}

Svelte allows us to provide a "class directive", or a class name in the form of class:NAME={boolean}. If we place a boolean (or function that returns a boolean) as its value, it will add the class "NAME" to the component when it returns true, or omit it when false.

This is extremely useful for navigation components, and I use it all the time to highlight active links in my UX/UI development process.

<NavBar>
    <Link href="#abc" class:active={page === 'abc'}>ABC</Link>
    <Link href="#xyz" class:active={page === 'xyz'}>XYZ</Link> 
</NavBar>

Flexible matching for the class attribute on both Svelte Components and HTML Elements.

Submitted by Nicholas Berlette (@nberlette) - 3 years ago