当前位置: 首页 > 文档资料 > Less 入门教程 >

字符串函数

优质
小牛编辑
125浏览
2023-12-01

字符串函数简介

字符串函数主要用于字符串的转码、替换、格式化等方面,可以帮助我们快速简便的处理字符串。

3.1 escape 函数

函数用途: 将URL编码应用于在输入字符串中找到的特殊字符。

tips:

  • 以下这些字符不会参与编码:, , / , ? , @ , & , + , ' , ~ , ! , $
  • 常见的编码字符: <space> , # , ^ , ( , ) , { , } , | , : , > , < , ; , ] , [, =

参数: string 需要转义的字符串。
返回值: 转义后的字符串,未带引号。
语法: escape(param) => value

  • 输入代码
.escape {
  string: escape('a=1')
}
  • 输出代码
.escape {
  string: a%3D1
}

3.2 e 函数

函数用途: CSS转义,替换为~"value"语法。

该函数可将字符串去除引号并返回。它可用于将输出无效的 CSS 值转换为 CSS 语法,或转换 Less 不能识别的专有语法。

参数:string 需要转义的字符。
返回值: string 去除引号后的转义字符。
语法: e(param) => value

  • 输入代码
.img {
  filter: e("ms:alwaysHasItsOwnSyntax.For.Stuff()");
}
  • 输出代码
.img {
  filter: ms:alwaysHasItsOwnSyntax.For.Stuff();
}

tips:

该函数还接受含 ~"" 的值和数字作为参数。其他类型的参数会报错。

3.3 % format 函数

函数用途: 格式化字符

第一个参数是带有占位符的字符串。所有占位符开始百分号 % 后跟字母 sSdDa ,或A 。其余参数包含替换占位符的表达式。如果需要输出百分比符号,请用另一个百分比将其转义 %%

如果需要将特殊字符转义为 utf-8 转义码,请使用大写占位符。该函数将转义除以外的所有特殊字符 ()'~!。空格编码为 %20 。小写占位符保留原样的特殊字符。

占位符:

  1. dDaA 可以通过任何种类的参数(颜色,号码,转义值,表达式,…)的替换。如果将它们与字符串结合使用,则将使用整个字符串-包括引号。但是,引号按原样放置在字符串中,不能用“/”或类似符号进行转义。
  2. sS 可以用任何表达式替换。如果将它与字符串一起使用,则仅使用字符串值-省略引号。

参数:

  • string : 带占位符字符串。
  • anything* : 用于替换占位符的值。

返回值:格式化后的字符串。

语法: %(string, anything) => value

  • 输入代码:
.format {
  format-a-d: %("repetitions: %a file: %d", 1 + 2, "directory/file.less");
  format-a-d-upper: %('repetitions: %A file: %D', 1 + 2, "directory/file.less");
  format-s: %("repetitions: %s file: %s", 1 + 2, "directory/file.less");
  format-s-upper: %('repetitions: %S file: %S', 1 + 2, "directory/file.less");
}
  • 输出代码:
.format {
  format-a-d: "repetitions: 3 file: "directory/file.less"";
  format-a-d-upper: "repetitions: 3 file: %22directory%2Ffile.less%22";
  format-s: "repetitions: 3 file: directory/file.less";
  format-s-upper: "repetitions: 3 file: directory%2Ffile.less";
}

3.4 replace 函数

函数作用: 替换字符串中的文本.

参数:

  • string :被替换的字符。
  • pattern: 需搜索的字符串或正则表达式。
  • replacement: 用于替换匹配模式的字符串。
  • flags:(可选)正则表达式标志。

返回值: 替换后的字符串。
语法: replace(string, pattern, replacement, ?flags) => value

  • 输入代码:
.replace {
  value: replace("Hello, Mars?", "Mars?", "Earth!");
}

  • 输出代码:
.replace {
  value: "Hello, Earth!";
}