Skip to content

Instantly share code, notes, and snippets.

@kazu69
Created January 8, 2014 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazu69/8311047 to your computer and use it in GitHub Desktop.
Save kazu69/8311047 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
// ----
// Sass (v3.3.0.rc.1)
// Compass (v0.13.alpha.10)
// ----
// String replace function
// @param $string: string to replace in
// @param $old: string to replace
// @param $new: string to replace $old into
// @param $case-sensitive: case sensitiveness
@function str-replace($string, $old, $new: '', $case-sensitive: true) {
// Checking for arguments accuracy
@if type-of($string) != string or type-of($old) != string or type-of($new) != string {
@warn "One of the 3 arguments is not a string.";
@return $string;
}
// Prevent from infinite recursion
@if str-index($new, $old) != 0 {
@warn "The string to be replaced is contained in the new string. Infinite recursion avoided.";
@return $string;
}
// Checking for case
$index: if(not $case-sensitive, str-index(to-lower-case($string), to-lower-case($old)), str-index($string, $old));
// Doing anything only if $old has been found
// And if new is different from old
@if $index > 0 and $new != $old {
$new-string: quote(str-slice($string, 1, $index - 1));
@for $i from $index through str-length($string) {
@if $i < $index or $i >= $index + str-length($old) {
$new-string: $new-string + str-slice($string, $i, $i);
}
}
// Going recursive
@return quote(str-replace(str-insert($new-string, $new, $index), $old, $new, $case-sensitive));
}
@return $string;
}
sass {
$string: "There you go, Hugo!";
replace: str-replace($string, "Hugo", "Nico");
$string: "Second example with some more letters, especially the letter E.";
replace: str-replace($string, "e", "z", false);
}
sass {
replace: "There you go, Nico!";
replace: "Szcond zxamplz with somz morz lzttzrs, zspzcially thz lzttzr z.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment