Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sass

I need an if statement in sass like the so:

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

Is there a way to do this?

like image 821
Shawn Cain Avatar asked Nov 02 '16 20:11

Shawn Cain


People also ask

Can I use if condition in SCSS?

In SASS we can make use of the if-else statement, and even else-if , just as we can do in programming languages.

How do you use interpolation in sass?

Interpolation can be used almost anywhere in a Sass stylesheet to embed the result of a SassScript expression into a chunk of CSS. Just wrap an expression in #{} in any of the following places: Selectors in style rules. Property names in declarations.

How do I write an if statement in sass?

An if statement is written with the @if rule, followed by the condition we want to evaluate and a code block. In the example above we check to see if the value of $circle is true. In this case it proved true so the code in the if statement's code block executed and the CSS was compiled with a radius of 50px .

What is #{} in SCSS?

is the css class selector, #{} interpolation syntax it allows the using of the variables in selectors and property names $name: foo; $attr: border; p.


2 Answers

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;
}
like image 150
Kodie Grantham Avatar answered Oct 19 '22 18:10

Kodie Grantham


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;
}
like image 38
Dmitry Shashurov Avatar answered Oct 19 '22 19:10

Dmitry Shashurov