SASS function to split strings is only splitting on first occurrence

Viewed 444

From the answer at https://stackoverflow.com/a/52375669/1427563 I used the following recursive SASS function to split a string into a list of substrings, given a separator. Eg calling str-split( "0 0 0 0", " "); should return the list ("0","0","0","0").

@function str-split( $string, $separator: " " ) {
    $i: str-index( $string, $separator );
    @if $i != null {
        @return append(
              str-slice( $string, 1, $i - 1 ),
              str-split( str-slice( $string, $i + str-length( $separator ) ), $separator )
        );
    }
    @return $string;
}

However calling the function with string "0 0 0 0" and separator " " returns the list ("0", "0 0 0"). This can be tested by checking the length of the returned array.

$sides_arr: str-split( "0 0 0 0", " " );
@debug length( $sides_arr );
> _2-mixins.scss:63 DEBUG: 2

The recursive call should ensure that the string is split at all occurrences. Why is the function str-split only splitting on the first occurrence of the separator?

2 Answers

Glad you found an alternative! I just remembered this question. Here is a str_split() function.

@function str_split($str, $substr) {
  $nList: ();

  @while str-index("#{$str}", "#{$substr}") != null {
    @if (str-index("#{$str}", "#{$substr}") > 1) {
      $nList: append(
        $nList,
        str-slice("#{$str}", 1, str-index("#{$str}", "#{$substr}") - 1)
      );
    }

    $str: str-slice(
      "#{$str}",
      str-index("#{$str}", "#{$substr}") + 1,
      str-length("#{$str}")
    );
  }

  @if (str-slice("#{$str}", 1, str-length("#{$str}")) != "") {
    $nList: append($nList, str-slice("#{$str}", 1, str-length("#{$str}")));
  }

  @return $nList;
}

For instance str_split(" x x x ", " ") will return "x" "x" "x".

https://codepen.io/LudwigGeorgImmanuel/pen/dypEzGB (you can use the commented out @error statement for debugging)

Not really an answer to the question asked, but an answer to the problem I had at hand:

A simple one-liner to split a string into an array based on a space separator is:

$array: nth( selector-parse( $string ), 1 );

This will split the string into an array of substrings, divided at whitespace. Thus. nth( selector-parse( "0 0 0 0" ), 1 ) will return ("0", "0", "0", "0").

Related