Str-erstatte funktion - CSS-tricks

Anonim

Sass giver en samling af praktiske funktioner til at manipulere strenge, men der er ingen funktion til at erstatte en substring med en anden streng. Her er en hurtig str-replacefunktion, hvis du nogensinde har brug for en.

/// 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; )

Anvendelse:

.selector ( $string: 'The answer to life the universe and everything is 42.'; content: str-replace($string, 'e', 'xoxo'); )

Resultat:

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