string.index()

The string.index() function returns index or list of indexes of $substrings.

// Sass.
@use 'sass:list';
@use 'sass:meta';
@use 'sass:string';

// The `string.index()` function.
@function index($string, $substring, $substrings...) {
  @if type-of($string) == string {
    $result: ();
    @each $substring in list.join($substring, $substrings, comma) {
      $result: list.append(
        $result,
        if(
          meta.type-of($substring) == string,
          string.index($string, $substring),
          null
        ),
        comma
      );
    }
    @if list.length($result) > 0 {
      @return if(list.length($result) == 1, list.nth($result, 1), $result);
    }
  }
  @return null;
}

Parameters

$string

The value to check whether it contains given $substring and/or $substrings.

$substring

A substring to find in $string.

$substrings...

The list of substrings to find in $string.

Return

The return value is the index or list of indexes of the given found substrings.

Examples

// Use.
@use '@angular-package/sass/math';

// Examples.
// Single
@debug string.index("Helvetica Neue", "Helvetica"); // 1
@debug string.index("Helvetica Neue", "Neue"); // 11

// Multiple
@debug string.index("Helvetica Neue", "Helvetica", "Neue"); // 1, 11
@debug string.index("Helvetica Neue", "Helvetica", "Neue", "Wrong"); // 1, 11, null
@debug string.index("Helvetica Neue", "Helvetica", "Neue", "Wrong", true); // 1, 11, null, null

// Different type of the `$string`
@debug string.index(true, "Helvetica"); // null

Last updated