Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim whitespace from a string in SASS?

Tags:

sass

How do you easily trim a string from whitespaces in sass? Preferably by choice from the start, the end of the string or both?

like image 357
Fredrik_Borgstrom Avatar asked Dec 06 '25 20:12

Fredrik_Borgstrom


1 Answers

Define the following sass functions:

    // Trims the start/left of the string:
    @function str-trimStart ($str) {
        @if (str-slice($str, 1, 1) == ' ') {
            @return str-trimStart(str-slice($str, 2));
        } @else {
            @return $str;
        }
    }

    // Trims the end/right of the string:
    @function str-trimEnd ($str) {
      @if (str-slice($str, str-length($str), -1) == ' ') {
            @return str-trimEnd(str-slice($str, 1, -2));
        } @else {
            @return $str;
        }
    }

    // Trims both the start and end of the string:
    @function str-trim ($str) {
      @return str-trimStart(str-trimEnd($str));
    }

Example of usage:

body {
    font-family: str-trim('  Some Font name  ');
}
like image 89
Fredrik_Borgstrom Avatar answered Dec 10 '25 15:12

Fredrik_Borgstrom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!