Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

css - SASS function to split strings is only splitting on first occurrence

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...