On this page
@std/text
Overview Jump to heading
Utility functions for working with text.
import { toCamelCase, compareSimilarity } from "@std/text";
import { assertEquals } from "@std/assert";
assertEquals(toCamelCase("snake_case"), "snakeCase");
const words = ["hi", "help", "hello"];
// Words most similar to "hep" will be at the front
assertEquals(words.sort(compareSimilarity("hep")), ["help", "hi", "hello"]);
Add to your project Jump to heading
deno add jsr:@std/text
See all symbols in @std/text on
为什么使用 @std/text? Jump to heading
当你需要可靠且经过充分测试的文本操作工具时,@std/text 是理想之选, 比如大小写转换、字符串相似度计算以及常用文本操作。
示例 Jump to heading
import { compareSimilarity, toKebabCase } from "@std/text";
console.log(toKebabCase("HelloWorld"));
const candidates = ["install", "init", "info"];
console.log(candidates.sort(compareSimilarity("in")));
查找最接近的建议 Jump to heading
import { closestString } from "@std/text/closest-string";
const options = ["length", "size", "help"];
console.log(closestString("hep", options)); // "help"
计算编辑距离 Jump to heading
import { levenshteinDistance } from "@std/text";
console.log(levenshteinDistance("kitten", "sitting")); // 3
按相似度排序列表 Jump to heading
import { wordSimilaritySort } from "@std/text";
const cmds = ["install", "init", "info", "inspect"];
console.log(wordSimilaritySort("in", cmds));
// 例如,输出:["init", "info", "install", "inspect"]
消除多行字符串缩进(不稳定) Jump to heading
import { dedent } from "@std/text/unstable-dedent";
const msg = dedent`
第一行
第二行
第三行
`;
console.log(msg);
// "第一行\n 第二行\n第三行\n"
支持 Unicode 的反转(不稳定) Jump to heading
import { reverse } from "@std/text/unstable-reverse";
console.log(reverse("mañana")); // "anañam"
// 保留像表情符号序列等的字符组合
console.log(reverse("👩❤️💋👨", { handleUnicode: true }));
小贴士 Jump to heading
- 使用相似度比较来实现命令行界面的模糊匹配和建议功能。
- 在可读性重要时,优先使用这些工具而非临时的正则表达式。
- 需要单个最佳建议时使用
closestString();需要对多个建议排序时使用wordSimilaritySort()。 - 部分工具标记为不稳定;通过
@std/text/unstable-*导入,并注意可能的 API 变动。