0
0
SASSmarkup~5 mins

Built-in string functions in SASS

Choose your learning style9 modes available
Introduction

Built-in string functions help you change and check text in your styles easily. They save time and make your code cleaner.

When you want to join two words or parts of text together.
When you need to check if a word or letter is inside a text.
When you want to locate the position of a substring in a string.
When you want to get a part of a text, like the first few letters.
When you want to find where a word or letter appears in text.
Syntax
SASS
function-name(string, [optional-arguments])
Most string functions take a string as the first input.
Some functions need extra information like the part of the string to get.
Examples
Returns the number of characters in the string "Hello".
SASS
string.length("Hello")
Returns the position where "Sass" first appears: 7 (positions start at 1).
SASS
string.index("Hello Sass", "Sass")
Inserts "hello " at position 1 in "world", resulting in "hello world".
SASS
string.insert("hello ", "world", 1)
Gets characters from position 2 to 4: "bcd".
SASS
string.slice("abcdef", 2, 4)
Sample Program

This Sass code uses built-in string functions to create a greeting by inserting "Hello " before "Sass". It then finds the length of the greeting and the position of "Sass" in it. The results show on the webpage with clear labels.

SASS
@use "sass:string";

$word: "Sass";
$greeting: string.insert("Hello ", $word, 7);
$length: string.length($greeting);
$position: string.index($greeting, $word);

body {
  font-family: Arial, sans-serif;
  padding: 1rem;
}

.result::before {
  content: "#{$greeting}";
  display: block;
  margin-bottom: 1rem;
}

.result {
  margin-bottom: 1rem;
  font-weight: bold;
}

.output-length::after {
  content: "Length: #{$length}";
  display: block;
  margin-top: 0.25rem;
  color: #555;
}

.output-position::after {
  content: "Position of \"Sass\": #{$position}";
  display: block;
  margin-top: 0.25rem;
  color: #555;
}
OutputSuccess
Important Notes

Remember to import the string module in Sass to use these functions.

Positions in strings start at 1, not 0.

String functions help keep your styles dynamic and easy to update.

Summary

Built-in string functions let you work with text inside your Sass code.

You can measure length, locate substrings, insert, and slice strings easily.

Using these functions makes your styles more flexible and powerful.