我们称一个字符序列为字符串。这几乎是所有编程语言中都有的基本类型之一。这里跟大家展示关于 JS 字符串的10个很棒的技巧,你可能还不知道哦?
7 g0 s- Y0 |% R- l' m; H0 P/ F/ l) ] 1.如何多次复制一个字符串 ( R- W4 z$ P4 W2 ~9 H+ d, J- D# e
JS 字符串允许简单的重复,与纯手工复制字符串不同,我们可以使用字符串的repeat方法。# A" T6 d9 J7 D5 w. q' D2 S2 k. C
const laughing = '小智'.repeat(3)
consol.log(laughing) // "小智小智小智"
const eightBits = '1'.repeat(8)
console.log(eightBits) // "11111111"2. 如何填充一个字符串到指定的长度 9 J' z" b: X D; q( t) B
有时,我们希望字符串具有特定长度。如果字符串太短,则需要填充剩余空间,直到达到指定的长度为止。过去,主要还是使用库 left-pad。但是,今天我们可以使用padStart和SpadEnd方法,选择哪种方法取决于是在字符串的开头还是结尾填充字符串。4 c! H8 s& l7 {
// 在开头添加 "0",直到字符串的长度为 8。
const eightBits = '001'.padStart(8, '0')
console.log(eightBits) // "00000001"
//在末尾添加“ *”,直到字符串的长度为5。
const anonymizedCode = "34".padEnd(5, "*")
console.log(anonymizedCode) // "34***"3.如何将字符串拆分为字符数组
$ o. M% R; B0 v4 B# Z 有多种方法可以将字符串分割成字符数组,我更喜欢使用扩展操作符(...):% j! b" E0 }3 d+ ~
const word = 'apple'
const characters = [...word]
console.log(characters) // ["a", "p", "p", "l", "e"] 注意,这并不总是像预期的那样工作。有关更多信息,请参见下一个技巧。
- e( U: h/ V4 r4 A5 W 4.如何计算字符串中的字符
; }% g) c4 r) s7 \( _1 e% { 可以使用length属性。$ r; t( J5 D& n; O) Z5 q5 {* y
const word = "apple";
console.log(word.length) // 5 但对于中文来说,这个方法就不太靠谱。
' i; b. B% [) r6 ? const word = "鲽"
console.log(word.length) // 2 汉字“鲽”返回length为2,为什么?JS 将大多数字符表示为16位代码点。但是,某些字符表示为两个(或更多)16 位代码点,称为代理对。如果使用的是length属性,JS 告诉你使用了多少代码点。因此,“鲽”由两个代码点组成,返回错误的值。 那怎么去判断呢,使用解构操作符号(...)
6 e! T1 p, u+ a2 C5 F const word = "鲽"
const characters = [...word]
console.log(characters.length) // 1 这种方法在大多数情况下都有效,但是有一些极端情况。例如,如果使用表情符号,则有时此长度也是错误的。如果真想计算字符正确长度,则必须将单词分解为 字素簇(Grapheme Clusters) ,这超出了本文的范围,这里就不在这说明。
: t; t. M( |0 V6 H: i* _ 5.如何反转字符串中的字符
$ q; ~7 G9 ~8 Z8 j L7 f7 p 反转字符串中的字符是很容易的。只需组合扩展操作符(...)、Array.reverse方法和Array.join方法。' t* v+ A7 E, y
const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa" 和前面一样,也有一些边缘情况。遇到边缘的情况就有需要首先将单词拆分为字素簇。" E' o/ g2 X0 O5 l$ x4 j0 e4 M9 U3 g$ L
6. 如何将字符串中的第一个字母大写 5 a4 m+ I" I* H) z. L
一个非常常见的操作是将字符串的第一个字母大写。虽然许多编程语言都有一种本地方法来实现这一点,但 JS 需要做一些工作。/ @" D3 h; X1 z8 x, _% x1 c% n
let word = 'apply'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // "Apple" 另一种方法:
' B1 W0 [9 l7 x2 g: }8 r. ^! T) U // This shows an alternative way
let word = "apple";
// 使用扩展运算符(`...`)拆分为字符
const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");
console.log(word); // "Apple"7.如何在多个分隔符上分割字符串
" ]# G& C- P0 ^7 F5 v6 Y 假设我们要在分隔符上分割字符串,第一想到的就是使用split方法,这点,智米们肯定知道。但是,有一点大家可能不知道,就是split可以同时拆分多个分隔符, 使用正则表达式就可以实现:3 {& V# P% f, ^7 E/ f( ~4 r
// 用逗号(,)和分号(;)分开。
const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]8.如何检查字符串是否包含特定序列
9 B# p2 X m9 n {7 o& @; n 字符串搜索是一项常见的任务。在 JS 中,你可以使用String.includes方法轻松完成此操作。不需要正则表达式。# s' ~; d0 B s" C
const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true9.如何检查字符串是否以特定序列开头或结尾 - j" e. ^1 w' l* D1 N% g
在字符串的开头或结尾进行搜索,可以使用String.startsWith和String.endsWith方法。3 X- O: E8 [6 Y; _6 {1 t
const text = "Hello, world! My name is Kai!"
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("world")); // false10.如何替换所有出现的字符串
4 a9 `- ^: U' ~ T# X 有多种方法可以替换所有出现的字符串。可以使用String.replace方法和带有全局标志的正则表达式。或者,可以使用新的String.replaceAll方法。请注意,并非在所有浏览器和Node.js 版本中都可用此新方法。. J& }0 x0 I7 d. d* ]/ u* R, H
const text = "I like apples. You like apples."
console.log(text.replace(/apples/g, "bananas"));
// "I like bananas. You like bananas."
console.log(text.replaceAll("apples", "bananas"));
// "I lik bananas. You like bananas."总结
4 h( a" _, P- ^+ l9 d: U' A3 N 字符串是几乎所有编程语言中最基本的数据类型之一。同时,它也是新开发人员学习的最早的数据类型之一。然而,尤其是在JavaScript中,许多开发人员并不知道关于字符串的一些有趣的细节。