String replace in Sass

前端 未结 2 1274
独厮守ぢ
独厮守ぢ 2021-02-12 18:15

Sass 3.2.1

How to replace in string some part of text? For example, remove from color #fefefe a dash #, to be fefefe.

Thanks!

2条回答
  •  走了就别回头了
    2021-02-12 18:32

    Here is a function that I just used!

    SCSS-FUNCTION

    /// Replace `$search` with `$replace` in `$string`
    /// @author Hugo Giraudel
    /// @param {String} $string - Initial string
    /// @param {String} $search - Substring to replace
    /// @param {String} $replace ('') - New value
    /// @return {String} - Updated string
    @function str-replace($string, $search, $replace: '') {
      $index: str-index($string, $search);
    
      @if $index {
        @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
      }
    
      @return $string;
    }
    

    SCSS-USAGE:

    .selector {
      $string: 'The answer to life the universe and everything is 42.';
      content: str-replace($string, 'e', 'xoxo');
    }
    

    SCSS-RESULT:

    .selector {
      content: "Thxoxo answxoxor to lifxoxo thxoxo univxoxorsxoxo and xoxovxoxorything is 42.";
    }
    

    Source of SCSS-example

    I use SASS with indented style, so this is my conversion to get a color variable to replace in a background with data:href inline encoded css svg-image. The # needs to be url-encoded and I use global colors that only needs to be replaced in one place and simply just work!

    SASS-FUNCTION:

    @function str-replace($string, $search, $replace: '')
      $index: str-index($string, $search)
      @if $index
        @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace)
      @return $string
    

    SASS-USAGE:

    $color-blue-night: #172b47    
    $icon-normal: str-replace('' + $color-blue-night, '#', '')
    

    or for a clear example

       .test
         color: str-replace('' + $color-blue-night, '#', '')
    

    SASS-RESULT:

    .test {
      color: "172b47"; }
    

提交回复
热议问题