很棒的 JavaScript 字符串技巧
如何多次复制一个字符串
1 2 3 4 5
| const laughing = '小智'.repeat(3) consol.log(laughing) // "小智小智小智"
const eightBits = '1'.repeat(8) console.log(eightBits) // "11111111"
|
填充一个字符串到指定的长度
1 2 3 4 5 6 7
| // 在开头添加 "0",直到字符串的长度为 8。 const eightBits = '001'.padStart(8, '0') console.log(eightBits) // "00000001"
//在末尾添加“ *”,直到字符串的长度为5。 const anonymizedCode = "34".padEnd(5, "*") console.log(anonymizedCode) // "34***"
|
将字符串拆分为字符数组
1 2 3
| const word = 'apple' const characters = [...word] console.log(characters) // ["a", "p", "p", "l", "e"]
|
计算字符串中的字符
可以使用length属性。
1 2
| const word = "apple"; console.log(word.length) // 5
|
但对于中文来说,这个方法就不太靠谱。
1 2
| const word = "𩸽" console.log(word.length) // 2
|
日本汉字𩸽返回length为2,为什么? JS 将大多数字符表示为16位代码点。 但是,某些字符表示为两个(或更多)16 位代码点,称为代理对。 如果使用的是length属性,JS 告诉你使用了多少代码点。 因此,𩸽(hokke)由两个代码点组成,返回错误的值。
那怎么去判断呢,使用解构操作符号(…)
1 2 3
| const word = "𩸽" const characters = [...word] console.log(characters.length) // 1
|
这种方法在大多数情况下都有效,但是有一些极端情况。 例如,如果使用表情符号,则有时此长度也是错误的。 如果真想计算字符正确长度,则必须将单词分解为 字素簇(Grapheme Clusters) ,这超出了本文的范围,这里就不在这说明。
如何反转字符串中的字符
1 2 3
| const word = "apple" const reversedWord = [...word].reverse().join("") console.log(reversedWord) // "elppa"
|
如何将字符串中的第一个字母大写
1 2 3
| let word = 'apply' word = word[0].toUpperCase() + word.substr(1) console.log(word) // "Apple"
|
在多个分隔符上分割字符串
1 2 3 4 5
| // 用逗号(,)和分号(;)分开。
const list = "apples,bananas;cherries" const fruits = list.split(/[,;]/) console.log(fruits); // ["apples", "bananas", "cherries"]
|
检查字符串是否包含特定序列
1 2
| const text = "Hello, world! My name is Kai!" console.log(text.includes("Kai")); // true
|
检查字符串是否以特定序列开头或结尾
1 2 3
| const text = "Hello, world! My name is Kai!" console.log(text.startsWith("Hello")); // true console.log(text.endsWith("world")); // false
|
填充一个字符串到指定的长度
String.replaceAll方法并非在所有浏览器和 Node.js 版本中都可用。
1 2 3 4
| const text = "I like apples. You like apples."
console.log(text.replace(/apples/g, "bananas")); // "I like bananas. You like bananas."
|