Skip to content

Instantly share code, notes, and snippets.

@jakob-e
Created January 4, 2015 17:25
Show Gist options
  • Save jakob-e/75775bac8ba2f898ac23 to your computer and use it in GitHub Desktop.
Save jakob-e/75775bac8ba2f898ac23 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
// ----
// Sass (v3.3.14)
// Compass (v1.0.1)
// ----
////
// I have written a lot of different `str-replace` Sass functions over
// the months yet none of my tries were succeeding in making the new substring
// able to contain the one to replace (e.g. `str-replace($str, "a", "ab")`).
// Thanks to Valérian Galliat (@valeriangalliat), I finally managed to build
// a bulletproof `str-replace` Sass function that allows new string to contain
// the old one.
////
/// Replace `$search` with `$replace` in `$string`
/// @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;
}
.test {
content: str-replace("a", "a", "a");
content: str-replace("a", "a", "ba");
content: str-replace("abc", "bc", "a");
content: str-replace("abcde", "bc", "a");
content: str-replace("abcde", "bcd", "bd");
}
.test {
content: "a";
content: "ba";
content: "aa";
content: "aade";
content: "abde";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment