JavaScript 字符串技巧(反转、分割、替换...)

字符串是几乎所有编程语言中的基本类型之一。总结了常用的使用技巧,那么,我们现在就开始吧。

1.如何多次复制一个字符串

JS 字符串允许简单的重复,不同于纯手工复制字符串,我们可以使用字符串重复的方法。

const str_repeat = 'MoMl'.repeat(3)
consol.log(str_repeat) // "MoMlMoMlMoMl"
2. 如何将字符串填充到指定长度

有时我们希望字符串具有特定的长度。如果字符串太短,则需要填充剩余空间,直到达到指定长度。

我们可以使用 padStartpadEnd 方法,选择取决于字符串是在字符串的开头还是结尾填充。

// Add "0" to the beginning until the length of the string is 8.
const str_padStart = '001'.padStart(8, '0')
console.log(str_padStart) // "00000001"

//Add " *" at the end until the length of the string is 5.
const str_padEnd = "34".padEnd(5, "*")
console.log(str_padEnd) // "34***"
3. 如何将一个字符串分割成一个字符数组

有几种方法可以将字符串拆分为字符数组,比如使用扩展运算符 (...)

const word = 'MoMl'
const cut_word = [...word]
console.log(cut_word)

也可以使用str.split("")

const word = 'MoMl'
const cut_word = word.split("")
console.log(cut_word)
4. 如何计算字符串中的字符

可以使用长度属性。

const word = "MoMl";
console.log(word.length) // 4
5.如何反转字符串中的字符

反转字符串中的字符很容易,只需组合扩展运算符 (...)、Array.reverse 方法和 Array.join 方法。

const word = "MoMl"
const reversed_word = [...word].reverse().join("")
console.log(reversed_word) // "lMoM"
6.如何将字符串中的第一个字母大写
let word = 'momo'
// word.substr(1):截取首字母后的字符
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // "Momo"

也可以:

let word = "momo";
const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");
console.log(word); // "Momo"
7. 如何在多个分隔符上拆分字符串

假设我们要在一个分隔符上拆分一个字符串,我们首先想到的就是使用split方法,这个方法当然是聪明人都知道的。但是,你可能不知道的一点是,split 可以同时拆分多个定界符,这可以通过使用正则表达式来实现。

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]
8. 如何检查字符串是否包含特定序列

字符串搜索是一项常见任务,在 JS 中,你可以使用 String.includes 方法轻松完成此操作,不需要正则表达式。

const text = "Hello, world! My name is MoMo"
console.log(text.includes("MoMo")); // true
9. 如何检查字符串是否以特定序列开始或结束

要在字符串的开头或结尾搜索,可以使用 String.startsWithString.endsWith 方法。

const text = "Hello, world! My name is MoMo!"
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("world")); // false
10.如何替换所有出现的字符串

有多种方法可以替换所有出现的字符串,您可以使用 String.replace 方法和带有全局标志的正则表达式;或者使用新的 String.replaceAll 方法,请注意,此新方法并非在所有浏览器和 Node.js 版本中都可用。

const text = "Hello, world! Hello, world!!"
console.log(text.replace(/world/g, "today"));
// "Hello, today! Hello, today!!"
console.log(text.replaceAll("world", "today"));

未完待续~~~

猜你喜欢

转载自blog.csdn.net/m0_65489440/article/details/128953149