KittyGiraudel / ama

Ask me anything!
43 stars 4 forks source link

SASS str-replace #121

Closed richware closed 2 years ago

richware commented 2 years ago

Hi, I am an 'old' software developer starting in 1971. I have been working with sass for about a year now and came across your str-replace function (https://css-tricks.com/snippets/sass/str-replace-function/). I just ran into a minor issue trying to do a str-replace for a list (or map) and got an error saying $string was not a string. No worries, I modified the str-replace (or should I say extended it) to a function str-replace-ex(same arguments)


@use "sass:list"
@use "sass:meta"

@function is-map($var)
  @return meta.type-of($var) == "map"

@function is-list($var)
  @return meta.type-of($var) == "list"

@function is-string($var)
  @return meta.type-of($var) == "string"

@function str-replace-ex($string, $search, $replace: "")
  @if is-list($string)
    $list: ()
    @each $sub-string in $string
      $list: list.append($list,str-replace($sub-string,$search,$replace))
    @return $list
  @else if is-string($string)
    @return str-replace($string,$search,$replace)
  @else
    @return $string
 
As you can see, it can be extended to include map variables too (all I needed right now was to replace values in a list). Thanks for your work in sass Regards, Rich
KittyGiraudel commented 2 years ago

Hey Rich!

Thank you for reaching out, that’s nice. ✨

You’re totally right, the function does expect a string as an input. In my opinion, the str-replace function should throw on anything but a string, but I could imagine how you’d have a nice use case for wanting to handle other types. That’s why I think the code you shared is pretty clean, and I like that you authored a wrapper around it instead of modifying the function itself.

Really neat! :)