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

时间:2015-09-03 13:03:56

标签: 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);

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

4 个答案:

答案 0 :(得分:9)

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

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;
}


用法

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

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

$split-values: str-split($values, ", ");
@each $value in $split-values {
  $list: append($list, str-split($value, " "));
}


转换为数字

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

答案 1 :(得分:0)

您可以通过少量自定义SASS功能实现此目的

@function split-str($string, $separator) {

   $index : str-index($string,  $separator);

   $str-1 : str-slice($string, 1, $index - 1);
   $str-2 : str-slice($string, $index + 1);

   @return $str-1 $str-2;
}

并像这样调用此函数,

$values: "10px 20px 30px , 20px 30px 40px";
$list : split-str($values, ',');
$m-1  : nth($list, 1);
$m-2  : nth($list, 2);

并确保在分隔符之前和之前留出空格

答案 2 :(得分: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
}

用法

$values: '15px 10px 5px';
$result: str-split($values, ' '); /* $result equals '15px' '10px' '5px' */

说明

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

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

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

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

要删除引号,可以在return语句中使用unquote($string)代替$string

答案 3 :(得分:-1)

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

如果您想要一个数字列表列表,请使用数字列表列表。