SyntaxStudy
Sign Up
SASS / SCSS String, List, and Selector Functions
SASS / SCSS Beginner 1 min read

String, List, and Selector Functions

The `sass:string` module provides functions for working with strings: `string.length()`, `string.slice()`, `string.to-upper-case()`, `string.to-lower-case()`, `string.index()`, and `string.insert()`. String functions are particularly useful inside mixins and functions that dynamically build selector names, CSS custom property names, or class name variants. The `sass:list` module enables working with SASS lists programmatically. Key functions include `list.nth()` to access items by index, `list.length()` to count items, `list.append()` to add items, `list.index()` to find the position of a value, and `list.join()` to concatenate two lists. Lists power many SASS patterns including multi-value property generation and loop-based utility class creation. The `sass:selector` module exposes the underlying selector engine. `selector.parse()` converts a selector string into a structured list, `selector.extend()` mirrors `@extend` logic as a function, `selector.replace()` substitutes one simple selector for another within a complex selector, and `selector.unify()` produces a selector matching elements matched by both inputs. These are advanced tools primarily useful for mixin library authors.
Example
// ── sass:string functions ─────────────────────────────────────────────────────

@use 'sass:string';
@use 'sass:list';
@use 'sass:selector';

// Build a BEM modifier selector string dynamically
@function bem($block, $element: null, $modifier: null) {
    $result: $block;

    @if $element  != null { $result: $result + '__' + $element; }
    @if $modifier != null { $result: $result + '--' + $modifier; }

    @return '.' + $result;
}

// Usage: bem('card', 'header', 'featured') → ".card__header--featured"

// Convert kebab-case to camelCase (basic implementation)
@function kebab-to-camel($string) {
    $parts  : string.split($string, '-');
    $result : list.nth($parts, 1);

    @for $i from 2 through list.length($parts) {
        $part   : list.nth($parts, $i);
        $result : $result + string.to-upper-case(string.slice($part, 1, 1))
                          + string.slice($part, 2);
    }

    @return $result;
}

// ── sass:list functions ───────────────────────────────────────────────────────

$breakpoints-list: 480px, 640px, 768px, 1024px, 1280px;
$labels          : xs, sm, md, lg, xl;

@each $bp in $breakpoints-list {
    $i     : list.index($breakpoints-list, $bp);
    $label : list.nth($labels, $i);

    .container-#{$label} {
        max-width: $bp;
        margin   : 0 auto;
        padding  : 0 1rem;
    }
}

// Append to a list and use it as a multi-value property
$shadows      : 0 1px 3px rgba(0,0,0,.1);
$hover-shadows: list.append($shadows, 0 4px 12px rgba(0,0,0,.15), $separator: comma);

.card {
    box-shadow: $shadows;
    &:hover { box-shadow: $hover-shadows; }
}