Sass 字串函式

Sass 中定義了各種型別的函式,其中大部分函式我們可以透過 CSS 語句直接呼叫。下面是 Sass 中的函式分類:

字串函式

數字函式

列表函式

對映函式

選擇器函式

Introspection函式

顏色值函式

本節我們先來學習字串相關函式。

字串函式有哪些

Sass 中的字串函式用於處理字串並獲取相關資訊。有一點需要注意,一般程式語言中字串的索引都是從 0開始的,但是注意喲,Sass 中字串的索引是從 1 開始的。

Sass 字串函式如下所示:

函式

描述

quote

給字串新增引號

unquote

移除字串的引號

str-length

返回字串的長度

str-index

返回 substring 子字串第一次在 string 中出現的位置。

str-insert

在字串 string 中指定索引位置插入內容

str-slice

從字串中擷取子字串,允許設定始末位置,未指定結束索引值則預設擷取到字串末尾

to-upper-case

將字串轉成大寫

to-lower-case

將字串轉成小寫

unique-id

返回一個無引號的隨機字串作為 id

quote函式

quote

函式主要用來給字串新增引號,如果字串本身就帶有引號,則會預設變為雙引號。

示例:

下面這個例子中,定義了兩個變數,這兩個變數的值都為字串,其中一個沒有帶引號,一個帶有單引號:

$str1: java;$str2: ‘python’; 。func1{ content: quote($str1);}。func2{ content: quote($str2);}

編譯成 CSS 程式碼:

。func1 { content: “java”;}。func2 { content: “python”;}

使用

quote()

函式給上述兩個字串新增引號後,不管原來的字串是帶有單引號還是不帶引號,最終兩個字串輸出後都預設帶有雙引號。

unquote函式

unquote

函式與

quote

函式功能相反,用於移除字串所帶的引號。

示例:

$str1: “hello,xkd”;。func1{ content: unquote($str1);}

編譯成 CSS 程式碼:

。func1 { content: hello,xkd;}

從輸出的 CSS 程式碼可以看出,經過

unquote()

函式處理的字串,所帶的雙引號會被移除。

str-length函式

str-length

函式用於返回字串的長度。此函式

示例:

。func{ content: str-length(“hello, xkd”);}

編譯成 CSS 程式碼:

。func { content: 10;}

從輸出的 CSS 程式碼可以看出,字串

hello,xkd

的長度為 10,這裡需要注意,空格也佔一個長度。

str-index函式

str-index

函式用於返回 substring 子字串第一次在 string 中出現的位置。其中

substring

string

都為函式引數。如果沒有匹配到子字串,則返回

null

示例:

。func{ content1: str-index(hello, o); content2: str-index(abc, a); content3: str-index(kiki, i);}

編譯成 CSS 程式碼:

。func { content1: 5; content2: 1; content3: 2;}

從上述程式碼中可以看出,當子字串在字串中出現多次時,例如

kiki

i

出現了兩次,使用

str-index()

函式後會返回子字串第一次出現時所在位置。

str-insert 函式

str-insert

函式用於在字串

string

中指定索引位置插入內容。第一個引數為字串,第二個引數為要插入的內容,第三個引數為要插入的位置。

示例:

例如要在

hello,

後面插入

xkd

。func { content: str-insert(“hello,”, “xkd”, 7);}

編譯成 CSS 程式碼:

。func { content: “hello,xkd”;}

上述程式碼中,因為

“hello,”

字串的長度為6,如果我們要在後面插入

xkd

,就要在 7 的位置插入。

str-slice 函式

str-slice

函式用於從字串中擷取子字串,允許設定開始和結束位置,當未指定結束索引值時,會預設擷取到字串末尾。

示例:

。func { content: str-slice(“abcdefg,”, 1, 3);}

編譯成 CSS 程式碼:

。func { content: “abc”;}

上述程式碼中,擷取字串中1到3之間的子字串,1表示擷取字串的開始位置,3表示擷取字串結束位置。

to-upper-case/to-lower-case 函式

to-upper-case

函式用於將字串轉成大寫,

to-lower-case

函式用於將字串轉成小寫。

示例:

$str:“Hello, XKD”;。func { content1: to-upper-case($str); content2: to-lower-case($str);}

編譯成 CSS 程式碼:

。func { content1: “HELLO, XKD”; content2: “hello, xkd”;}

unique-id函式

unique-id

函式返回一個無引號的隨機字串作為 id。

示例:

。func { content: unique-id();}

編譯成 CSS 程式碼:

。func { content: uo50mf1eb;}

連結:https://www。9xkd。com/Sass 字串函式