String replace in Sass

≯℡__Kan透↙ 提交于 2021-02-06 15:09:53

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/12728634/string-replace-in-sass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!