Sass String Functions

Sass Tutorial

Sass String Functions

Sass String Functions are used to manipulate text values (strings) such as class names, file paths, font names, and dynamic selectors.
They are very useful when working with dynamic CSS, theming, and utility classes.


 What Is a String in Sass?

A string can be:

  • Quoted → "Helvetica"

  • Unquoted → Helvetica

$font: "Roboto";

 Common Sass String Functions


1️⃣ quote()

Adds quotes to a string.

quote(Helvetica);

✔ Output:

"Helvetica"

2️⃣ unquote()

Removes quotes from a string.

unquote("Arial");

✔ Output:

Arial

3️⃣ str-length()

Returns the number of characters in a string.

str-length("Sass");

✔ Output:

4

4️⃣ str-insert()

Inserts a string at a specific position.

str-insert("Hello World", " Sass", 6);

✔ Output:

"Hello Sass World"

5️⃣ str-index()

Finds the position of a substring.

str-index("frontend", "end");

✔ Output:

6

(Returns null if not found)


6️⃣ str-slice()

Extracts part of a string.

str-slice("stylesheet", 1, 5);

✔ Output:

"style"

7️⃣ to-upper-case()

Converts string to uppercase.

to-upper-case("sass");

✔ Output:

"SASS"

8️⃣ to-lower-case()

Converts string to lowercase.

to-lower-case("SASS");

✔ Output:

"sass"

 String Interpolation (#{})

Used to insert variables into strings or selectors.

$size: large;

.btn-#{$size} {
padding: 20px;
}

✔ Output:

.btn-large {
padding: 20px;
}

 Real-Life Example (Dynamic Class Names)

$theme: dark;

body.#{$theme}-mode {
background: black;
color: white;
}


 Example: File Path Handling

$img-path: "images";

.banner {
background-image: url(“#{$img-path}/banner.jpg”);
}


❗ Notes & Best Practices

✔ Use strings for dynamic CSS
✔ Prefer interpolation over concatenation
✔ Remember: Sass strings are 1-based indexed
✔ Be careful with quoted vs unquoted strings


📌 Summary

  • It provides powerful string functions

  • Useful for dynamic selectors & paths

  • Works great with interpolation

  • Helps reduce repetition and errors

You may also like...