写在前面
字符串原始值本身是没有属性和方法的,在调用相关属性和方法时后台会创建对应的原始包装类型对象,进而暴露出属性和方法
举个例子:
let str="hello,world"
console.log(str.length) //11
在第二行打印语句相当于执行了如下代码:
let str=new String("hello,world") //临时创建一个String实例
console.log(str.length) //11
在执行打印语句后创建的String实例对象会被销毁
书归正传
从超类继承的三个方法:valueOf()、toLocaleString()、toString()。他们返回原始值字符串
const str = "hello"
console.log(str.valueOf()) //hello
console.log(str.toLocaleString()) //hello
console.log(str.toString()) //hello
charAt(index) 返回指定索引位置的字符
const str = "hello,world"
console.log(str.charAt(4)) //o
console.log(str.charAt(5)) //,
concat(value1,value2…) 拼接字符串,可接受多个参数,将其拼接并返回(原字符串不变)
const str1="kobe"
const str2="hello"
let s=str2.concat("--",str1)
console.log(s) //hello--kobe
这个方法和用+拼接字符串效果是一样的
三个从字符串中提取子字符串的方法(返回截取字符串,不改变原字符串) : slice、substring、substr
- slice(value1,value2) 和 substring(value1,value2) 方法类似 :
参数为正数时
两个方法都是返回索引从value1到value2的子字符串,区间 [value1,value2) 不包括索引值为value2的字符,如果省略第二个参数,那么表示从索引值value1一直截取到最后并返回。
const str1="hello,world"
console.log(str1.slice(2,4)) //ll(注意,是闭开区间)
console.log(str1.slice(2)) //llo,world
console.log(str1.substring(2,4)) //ll(注意,是闭开区间)
console.log(str1.substring(2)) //llo,world
当参数为负数时
slice方法将所有负数参数转换为字符串长度加该负数参数处理
console.log(str1.slice(-3)) //rld 从索引为8的位置截取到末尾
console.log(str1.slice(-3,-1)) //rl [8,10)
substring方法将所有负数参数转换为0处理
console.log(str1.substring(-3)) //hello,world
- substr(value1,value2) 该方法第一个参数为截取开始的索引,第二个参数为截取的个数,省略则截取到末尾
const str1="hello,world"
console.log(str1.substr(2,4)) //llo,
console.log(str1.substr(2)) //llo,world
对于参数是负值的情况,substr会将第一个负值参数转换为数组长度加该负数,第二个负值参数转换为0
console.log(str1.substr(-3)) //rld
console.log(str1.substr(3,-4)) //""(空)
搜索子字符串位置的方法 :indexOf()、lastIndexOf()
这两个方法都是从指定字符串中搜索参数字符串的位置,第一个参数为参数字符串,第二个参数是起始位置,可以省略。二者区别就是: indexOf是从前往后搜索,lastIndexOf是从后往前搜索。找不到则返回-1
const str1="hello,world"
console.log(str1.indexOf("lo")) //3
console.log(str1.lastIndexOf("lo")) //3
console.log(str1.indexOf("le")) //-1
判断是否包含另一个字符串的方法:includes()
参数是用于搜索的字符串,可以加第二个参数,表示开始搜索位置
const str1="hello,world"
console.log(str1.includes("wor")) //true
trim()
该方法会创建字符串的一个副本,去掉前后空格并放回
const str1=" hello,world "
console.log(str1.trim()) //hello,world
console.log(str1.trim().length) //11
repeat
该方法参数为一个整数,将字符串复制指定次数并拼接成一个副本返回
const str1="hello"
console.log(str1.repeat(3)) //hellohellohello
转化成数组的一个方法:split()
该方法接收两个参数,第一个参数为字符串或正则表达式,第二个参数为数组长度(可选) 该方法返回一个数组:该数组是由第一个参数分割后的子字符串组成的
const str="h,e,l,l,o,w,o,r,l,d"
let str1=str.split(",")
console.log(str1) //Array(10) [h,e,l,l,o,w,o,r,l,d]
字符串还有其他的方法,这里只是一部分常用的,今天就先写到这。