如何在SASS中将字符串拆分为两个数字列表?

Dar*_*ski 5 css sass

我有一个SASS/SCSS字符串,其中包含两个列表(以逗号分隔),每个列表包含数字(由空格分隔).如何将字符串拆分为两个数字列表?

SCSS:

$values: "10px 20px 30px, 20px 30px 40px";

$begin: /* should be */ "10px", "20px", "30px";
$end: /* should be */ "20px", "30px", "40px";

// optionally it can be a map:
$begin: (10px, 20px, 30px);
$end: (20px, 30px, 40px);
Run Code Online (Sandbox Code Playgroud)

关于Sass Meister的代码:http: //sassmeister.com/gist/4d9c1bd741177636ae1b

小智 12

好吧,你可以用这个函数拆分字符串:

STR-分裂

@function str-split($string, $separator) {
    // empty array/list
    $split-arr: ();
    // first index of separator in string
    $index : str-index($string, $separator);
    // loop through string
    @while $index != null {
        // get the substring from the first character to the separator
        $item: str-slice($string, 1, $index - 1);
        // push item to array
        $split-arr: append($split-arr, $item);
        // remove item and separator from string
        $string: str-slice($string, $index + 1);
        // find new index of separator
        $index : str-index($string, $separator);
    }
    // add the remaining string to list (the last item)
    $split-arr: append($split-arr, $string);

    @return $split-arr;
}
Run Code Online (Sandbox Code Playgroud)


用法

在您的情况下,您可以这样使用它:

$values: "10px 20px 30px, 20px 30px 40px";
$list: ();

$split-values: str-split($values, ", ");
@each $value in $split-values {
  $list: append($list, str-split($value, " "));
}
Run Code Online (Sandbox Code Playgroud)



转换为数字

至于将字符串值转换为数字,请查看Hugo Giraudel在SassMeister上的功能(或阅读他的博客文章)

  • 您可能需要将 `$string: str-slice($string, $index + 1);` 替换为 `$string: str-slice($string, $index + str-length($separator));` 以支持长度超过 1 个字符的分隔符 (2认同)

Luc*_*Luc 6

递归函数也可以工作。

功能

@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
}
Run Code Online (Sandbox Code Playgroud)

用法

$values: '15px 10px 5px';
$result: str-split($values, ' '); /* $result equals '15px' '10px' '5px' */
Run Code Online (Sandbox Code Playgroud)

解释

var$i对应于给定 中第一个分隔符出现的索引$string

结束递归的条件是确保余数中不存在分隔符。

str-split该函数返回一个列表,其中包含第一个分隔符出现之前的子字符串以及该函数以剩余子字符串作为参数返回的值。

请注意,str-length用于启用超过 1 个字符的分隔符。

要删除引号,您可以在返回语句中使用unquote($string)而不是。$string


cim*_*non -3

您不需要,至少没有第三方库(这几乎肯定需要用 Ruby 编写的自定义函数)。即使 Sass 有一个用于分割字符串的本机函数,它也没有办法将字符串转换为数字(我怀疑它永远不会)。

如果您需要数字列表的列表,请使用数字列表的列表。