字符串技巧
呛再首 6/12/2020 javascript面试
# 填充字符串到指定长度
过去,主要还是使用库 left-pad。 但是,今天我们可以使用padStart和padEnd方法,选择哪种方法取决于是在字符串的开头还是结尾填充字符串。
// 在开头添加 "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
4
5
6
7
2
3
4
5
6
7
# 在多个分隔符上分割字符串
搭配正则表达式 split 可以同事拆分多个分隔符。
// 用逗号(,)和分号(;)分开。
const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]
1
2
3
4
2
3
4
# 检查字符串是否包含特定序列
使用 String.includes 可以实现字符串搜索
const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true
1
2
2
# 检查字符串是否以特定序列开头或结尾
在字符串的开头或结尾进行搜索,可以使用String.startsWith和String.endsWith方法
const text = "Hello, world! My name is Kai!"
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("world")); // false
1
2
3
4
5
2
3
4
5
# 将字符串的首字母转换成大写字母
const toUpperFirstLetter = ([first, ...rest]) => first.toUpperCase() + rest.join('');
1