返回

重学 JS:一图掌握 JS 字符串

前端

重学 JS,从字符串开始

前端开发的第三年,突然发现,对于 JS,我还有很多不懂的地方,趁着最近需求少,不如静下心来,从头把 JS 再学一遍,查漏补缺。

首先从最基础的字符串开始,通过一张全面的图表,帮助大家快速掌握 JS 字符串的常用操作方法,轻松应对各种字符串处理任务。

一图掌握 JS 字符串

方法 语法 示例
length 获取字符串的长度 str.length "Hello world!".length // 13
charAt 获取指定位置的字符 str.charAt(index) "Hello world!".charAt(0) // "H"
charCodeAt 获取指定位置字符的 Unicode 编码 str.charCodeAt(index) "Hello world!".charCodeAt(0) // 72
indexOf 搜索指定子字符串的首次出现位置 str.indexOf(substr) "Hello world!".indexOf("world") // 6
lastIndexOf 搜索指定子字符串的最后一次出现位置 str.lastIndexOf(substr) "Hello world!".lastIndexOf("world") // 11
slice 提取指定范围的字符串 str.slice(start, end) "Hello world!".slice(0, 5) // "Hello"
substring 提取指定范围的字符串,不包含 end 位置的字符 str.substring(start, end) "Hello world!".substring(0, 5) // "Hello"
substr 提取指定范围的字符串,支持负数索引 str.substr(start, length) "Hello world!".substr(1, 4) // "ello"
replace 替换指定子字符串 str.replace(substr, newSubstr) "Hello world!".replace("world", "universe") // "Hello universe!"
toUpperCase 将字符串转换为大写 str.toUpperCase() "Hello world!".toUpperCase() // "HELLO WORLD!"
toLowerCase 将字符串转换为小写 str.toLowerCase() "Hello world!".toLowerCase() // "hello world!"
trim 删除字符串两端的空格 str.trim() " Hello world! ".trim() // "Hello world!"
split 将字符串按指定分隔符拆分为数组 str.split(separator) "Hello world!".split(" ") // ["Hello", "world!"]
join 将数组中的元素连接成一个字符串 arr.join(separator) ["Hello", "world!"].join(" ") // "Hello world!"

总结

以上表格列出了 JS 字符串的常用操作方法,希望对大家学习 JS 字符串有所帮助。

当然,学习 JS 字符串不仅仅是掌握这些方法,更重要的是理解这些方法的原理和应用场景,才能灵活地运用它们解决实际问题。

所以,在掌握了这些方法的基础上,大家还可以通过阅读文档、查阅博客、练习编码等方式进一步巩固和加深对 JS 字符串的理解和应用能力。