# 字符串常用技巧
1.如何多次复制一个字符串:
JS 字符串允许简单的重复,不同于纯手工复制字符串,我们可以使用字符串重复的方法。
const laughing = 'Maxwell '.repeat(3)
consol.log(laughing) // "Maxwell Maxwell Maxwell "
const eightBits = '1'.repeat(8)
console.log(eightBits) // "11111111"
1
2
3
4
5
6
7
2
3
4
5
6
7
2.如何将字符串填充到指定长度:
- 有时我们希望字符串具有特定的长度。如果字符串太短,则需要填充剩余空间,直到达到指定长度。
- 以前主要用库left-pad。但是,今天我们可以使用 padStart 和 SpadEnd 方法,选择取决于字符串是在字符串的开头还是结尾填充。
// Add "0" to the beginning until the length of the string is 8.
const eightBits = '001'.padStart(8, '0')
console.log(eightBits) // "00000001"
//Add " *" at the end until the length of the string is 5.
const anonymizedCode = "34".padEnd(5, "*")
console.log(anonymizedCode) // "34***"
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
3.如何将一个字符串分割成一个字符数组:
const word = 'Maxwell'
const characters = [...word]
console.log(characters)
1
2
3
2
3
4.如何反转字符串中的字符:
const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa"
1
2
3
2
3
5.如何将字符串中的第一个字母大写:
let word = 'apply'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // "Apple"
方法二
function upperFirstLetter (s) {
const [a, ...rest] = [...s];
return [a.toUpperCase(), ...rest].join('')
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
6.如何在多个分隔符上拆分字符串:
const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]
1
2
3
2
3
7.如何检查字符串是否包含特定序列:
const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true
1
2
2
8.如何检查字符串是否以特定序列开始或结束:
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
6
7
2
3
4
5
6
7
9.如何替换所有出现的字符串:
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"));
1
2
3
4
5
6
2
3
4
5
6