Is there a way in SASS to do if string contains or ends with?

Because I was just searching for this, I'll add this option: index. index($list, $value) returns an int (the 1-based index) or null meaning it can be used in a boolean context.

Here's a nice use-case:

@mixin flexbox($args:'') {
    @if index($args, 'inline') {
        display: inline-flex;
    } @else {
        display: flex;
    }

    @if index($args, 'bar') == null {
        /* style if 'bar' ISN'T passed */
    }
}

.foo {
    @include flexbox(inline);
}

You can create pleasantly sophisticated mixins and for-loops with a single string of space-concatenated keywords instead of maps. (Think of how browsers process background: red url(image.png) no-repeat center;)


Not exactly what you were looking for, but I think it's about as close as you can get with Sass.

Using str-index($string, $substring) you can find out if $name contains -outline:

@each $name, $char in $font-icons {
    @if (str-index($name, '-outline')) {
        //do something
    }
}

EDIT: Just wrote a quick Sass function to actually find out if the string ends with another string:

@function ends-with($string, $find) {
  @if (str-index($string, $find) == (str-length($string) - str-length($find) + 1)) {
    @return true;
  } @else {
    @return false;
  }
}

@each $name, $char in $font-icons {
    @if (ends-with($name, '-outline')) {
        //do something
    }
}

UPDATE #2: The function above will return false if $string contains $find more than once. This function will return true if $string truly ends with $find:

@function ends-with($string, $find) {
  @if (str-slice($string, (str-length($string) - str-length($find) + 1)) == $find) {
    @return true;
  } @else {
    @return false;
  }
}

UPDATE #3: Simplified:

@function ends-with($string, $find) {
  @return str-slice($string, (str-length($string) - str-length($find) + 1)) == $find;
}

Use this SCSS code:

@function str-ends-with($string, $find) {
    @return str-length($string) >= str-length($find) AND str-slice($string, (str-length($string) - str-length($find) + 1)) == $find;
}

Tags:

Sass