Less - 字符串函数
LESS - 字符串函数
Section titled “LESS - 字符串函数”LESS 提供了几种内置函数用于操作字符串。这些函数对于诸如 URL 编码、动态字符串生成、转义 CSS 中的特殊字符、格式化文本以及替换子字符串等任务非常有用。这些能力使得样式表的生成更加动态和灵活。
以下是一些 LESS 中常用的字符串函数:
| 序号 | 函数与描述 | 示例(概念性 LESS 及输出) |
|---|---|---|
| 1 | escape(string) 对字符串中的特殊字符进行 URL 编码,使其可以安全地用于 URL 中。例如,空格变为 %20,! 变为 %21。 | escape(“Hello!! welcome to http://example.com?q=less rocks”); |
// Output: “Hello%21%21%20welcome%20to%20http%3A%2F%2Fexample.com%3Fq%3Dless%20rocks” | ||
| 2 | e(string) 接受一个字符串作为输入,并将其内容直接输出到 CSS 中,不带引号(它“转义”了 LESS 的字符串处理)。这对于输出 LESS 可能误解的 CSS 值或在 CSS 中不能带引号的值非常有用。 | filter: e(“progid:DXImageTransform.Microsoft.Alpha(opacity=50)”); |
// Output: filter: progid:DXImageTransform.Microsoft.Alpha(opacity=50); |
// 现代更简单的字符串插值替代方案(通常更推荐):
@my-font-stack: "Helvetica Neue", Arial, sans-serif;
font-family: ~"@{my-font-stack}";
// Output: font-family: Helvetica Neue, Arial, sans-serif; | | 3 | %(string, arguments...) 或 sprintf(string, arguments...)
通过用提供的参数替换占位符来格式化字符串。类似于其他语言中的 `sprintf`。
占位符:
`%s` - 将参数插入为字符串。
`%d` - 将参数插入为整数(截断小数部分)。
`%a` - 按原样插入参数(如果不是字符串,则将其字符串化;如果是带引号的字符串,则保留引号)。
`%S`, `%D`, `%A` - 转义版本。 | format-example: %("Path: %s, Count: %d, Status: %a", "/img/logo.png", 5.8, 'active');
// Output: format-example: "Path: /img/logo.png, Count: 5, Status: 'active'";
@image-path: "/assets/images";
background-image: url(%( "%s/background.jpg", @image-path));
// Output: background-image: url("/assets/images/background.jpg"); | | 4 | replace(string, pattern, replacement, flags)
将字符串中匹配模式(字符串或正则表达式)的部分替换为替换字符串。可以提供可选的正则表达式标志(例如,`i` 表示不区分大小写,`g` 表示全局)。 | // 简单的字符串替换:
replace("Hello, World!", "World", "LESS", "");
// Output: "Hello, LESS!"
// 正则表达式替换(移除所有数字,全局标志 'g'):
replace("Product-123-Version-45", "\\d+", "", "g");
// Output: "Product--Version-"
// 正则表达式替换,不区分大小写 'i':
replace("Image.JPG", "\\.jpg$", ".png", "i");
// Output: "Image.png" |
- 字符串插值
@{variable}: 这是将变量值插入字符串的最常用方式:@path: "images"; background: url("@{path}/bg.png");结果是background: url("images/bg.png");。 - 波浪号转义
~"...": 若要输出不带引号且不让 LESS 尝试解释其内容的字符串值,请使用波浪号转义:filter: ~"ms:alwaysHasAlpha(true)";。
选择正确的字符串操作技术取决于具体需求,但理解这些函数和插值方法可以为 CSS 输出提供强大的控制。