SCSS: Extract values from within variable

Viewed 112

I'm trying to extract values from an SCSS variable that contains 1+ values. For testing purposes, let's say I want to get the 2nd value of the argument passed in, and if it only contains 1 value, then return that. e.g.

@function get-second-value($args) {
  // Obviously this syntax isn't correct, but something like this
  @return $args.split(' ')[1] || $args;
}

$var1: 1px;
$var2: 1px 2px;
$var3: 1px 2px 3px;

@debug get-second-value($var1);  // returns 1px
@debug get-second-value($var2);  // returns 2px
@debug get-second-value($var3);  // returns 2px

I've tried searching all over, but my search terms must be inadequate, so apologies if this is a dupe. How can I accomplish the above?

1 Answers

I think I figured it out... I didn't realize that the variable I was defining was actually a list, so I can do normal list operations on it. My function then becomes:

@function get-second-value($args) {
    $return: nth($args, 1);
    @if (length($args) > 1) {
        $return: nth($args, 2);
    }
    @return $return;
}
Related