String replace in Sass

前端 未结 2 1271
独厮守ぢ
独厮守ぢ 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"; }
    
    0 讨论(0)
  • 2021-02-12 18:56

    Simple temporary solution (in my case for Mac):

    $ git clone -b string_functions https://github.com/chriseppstein/sass
    $ cd sass
    $ sudo rake install
    
    $ sudo mv /usr/bin/sass /usr/bin/sass.orig
    $ sudo ln -s /Library/Ruby/Gems/1.8/gems/sass-3.2.0.alpha.0/bin/sass /usr/bin/sass
    
    0 讨论(0)
提交回复
热议问题