萨斯 3.2.1
如何在字符串中替换部分文本?例如,从颜色#fefefe 中删除一个破折号#,成为fefefe。
谢谢!
这是我刚刚使用的一个功能!
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 用法:
.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.";
}
我使用带有缩进样式的 SASS,所以这是我的转换,以获取在背景中用 data:href 内联编码的 css svg-image 替换的颜色变量。# 需要进行 url 编码,我使用全局颜色,只需要在一个地方替换就可以了!
SASS 功能:
@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 用法:
$color-blue-night: #172b47
$icon-normal: str-replace('' + $color-blue-night, '#', '')
或举个明显的例子
.test
color: str-replace('' + $color-blue-night, '#', '')
SASS结果:
.test {
color: "172b47"; }
简单的临时解决方案(以我的 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