目录
包装类简介
JS中一共有5个包装类:
String --> 字符串包装为String对象
Number --> 数值包装为Number对象
Boolean --> 布尔值包装为Boolean对象
BigInt --> 大整数包装为BigInt对象
Symbol --> 符号包装为Symbol对象
通过包装类可以将一个原始值包装为一个对象, 当我们对一个原始值调用方法或属性时,JS解释器会临时将原始值包装为对应的对象,然后调用这个对象的属性或方法。这也就是为什么number,string这些基本类型也有属性和方法的原因。
由于原始值会被临时转换为对应的对象,这就意味着对象中的方法都可以直接通过原始值来调用
在JS中,除了直接创建原始值外,也可以创建原始值的对象,但是千万不要这么做,没有意义,这应该是浏览器做的。
通过 new String() 可以创建String类型的对象 通过 new Number() 可以创建Number类型的对象 通过 new Boolean() 可以创建Boolean类型的对象
也就是说包装类不是给我们用的,是js自己用的。
字符串的方法
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
概念
1.字符串可以理解为是一个字符数组,它可以像数组一样根据索引获得。
-"hello" --> ["h", "e", "l", "l", "o"];字符串的很多方法都和数组是非常类似的
2.在JavaScript中,字符串(String)是一种基本的数据类型,用于表示文本。
3.它是由零个或多个Unicode字符组成的字符序列。
4.字符串可以用单引号 (') 或双引号 (") 来包围。两者在功能上等价,但需确保开始和结束引号匹配。
5.模板字符串(Template Literals):ES6引入的新特性,使用反引号(```)包围,并支持嵌入表达式。
属性
1.字符串[索引] 获取指定位置的字符
通过索引来访问字符串中的单个字符,索引从0开始。
let str = "Hello";
console.log(str[0]); // 输出 "H"
2.length 获取字符串的长度
使用.length属性获取字符串的长度。
let str = "Hello";
console.log(str.length); // 输出 5
字符串方法
方法 | 描述 |
---|---|
str.at() (实验方法) | 根据索引获取字符,可以接受负索引 |
str.charAt() | 根据索引获取字符 |
str.concat() | 用来连接两个或多个字符串 |
str.includes() | 用来检查字符串中是否包含某个内容, 有返回true ,没有返回false |
str.indexOf() | 查询字符串中第一次出现的 查询内容的索引,如果未找到则返回 -1 |
str.lastIndexOf() | 查询字符串中最后一次出现的 查询内容的索引,如果未找到则返回 -1 |
str.startsWith() | 检查一个字符串是否以指定内容开头 |
str.endsWith | 检查一个字符串是否以指定内容结尾 |
str.padStart() | 用给定字符串从开头填充当前字符串并返回新字符串的长度 |
str.padEnd() | 用给定字符串从末尾填充当前字符串并返回新字符串的长度。 |
str.replace() | 使用一个新字符串替换一个指定内容 |
str.replaceAll() | 使用一个新字符串替换所有指定内容 |
str.slice() | 对字符串进行切片 |
str.substring() | 截取字符串 |
str.split() | 用来将一个字符串拆分为一个数组 |
str.toLowerCase() | 将字符串转换为小写 |
str.toUpperCase() | 将字符串转换为大写 |
str.trim() | 去除前后空格 |
str.trimStart() | 去除开始空格 |
str.trimEnd() | 去除结束空格 |
repeat() | 将字符串复制指定次数。 |
实例
substring() 方法
substring() 类似于 slice()。不同之处在于 substring() 无法接受负的索引。如果省略第二个参数,则该 substring() 将裁剪字符串的剩余部分。
var str = "Apple, Banana, Mango";
var res = str.substring(7,13);
console.log(res)//Banana
trim()
功能: 从一个字符串的两端删除空白字符。
var str =" 2021, 希望过的开开心心!! "
console.log(str.trim())//2021, 希望过的开开心心!!
综合
let str = "hello"
console.log(str[0])//h
console.log(str.at(0))//h
console.log(str.charAt(0))//h
str = "hello hello how are you"
console.log(str.includes("how", 13))//false
console.log(str.endsWith("you"))//true
str = "100"
console.log(str.padStart(7, "0"))//0000100
str = "hello hello how are you"
let result = str.replace("hello", "abc")
console.log(result)//abc hello how are you
result = str.replaceAll("hello", "abc")
console.log(result)//abc abc how are you
result = str.slice(12, 17)
console.log(result)//how a
result = str.substring(12, 17)
console.log(result)//how a
result = str.substring(17, 12)
console.log(result)//how a
str = "abc@bcd@efg@jqk"
result = str.split("@")
console.log(result)// ["abc", "bcd", "efg", "jqk"]
str = "abcdABCD"
result = str.toLowerCase()
console.log(result)//abcdabcd
str = " ab c "
console.log(result)//ab c