Sass中的字符串替换

时间:2012-10-04 13:43:23

标签: sass

Sass 3.2.1

如何在字符串中替换部分文本?例如,从颜色#fefefe中删除短划线#,为fefefe。

谢谢!

2 个答案:

答案 0 :(得分:19)

这是我刚才使用的功能!

<强> 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-结果:

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

Source of SCSS-example

我使用缩进样式的SASS ,所以这是我的转换,以获取颜色变量以在背景中替换数据:href inline encoded css svg-image。 #需要进行网址编码,我使用全局颜色,只需要在一个地方更换,只需要工作!

<强> 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, '#', '')

或明确的例子

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

<强> SASS-结果:

.test {
  color: "172b47"; }

答案 1 :(得分:0)

简单的临时解决方案(在我的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