(一)获取字符串的长度

通过length这个属性,来获取字符串的长度:

let a = `123456`
console.log(a.length); // 6

注意 ,这里length是属性,不是方法,不需要加括号()。

(二)访问字符

我们可以通过 [ ] 中括号或者charAt()的方式来进行访问:

let a = `123456`
console.log(a[2]); // '3'
console.log(a.charAt(2)); // '3'

通过两种方式,我们都能过获取到字符串中对应的内容。两者唯一的区别就在于,没有找到对应的字符的话,[ ]的方式返回的值是undefined,而charAt返回的是空:

let a = `123456`
console.log(a[10]); // undefined
console.log(a.charAt(10)); // 空

(三)改变大小写

toLowerCase() 大写改小写,toUpperCase()小写改大写

let a = `aBcD`
console.log(a.toLowerCase()); // abcd
console.log(a.toUpperCase()); // ABCD

(四)查找子字符串

(1)str.indexOf(substr,pos),从pos下标开始,在str中从pos下标开始查找substr,找到则返回成功的位置,没有找到则返回-1:

let a = `abcdefg`
console.log(a.indexOf('c',0)); // 2
console.log(a.indexOf('h',0)); // -1 没有返回-1

(2)从字符串的末尾开始,以相反的顺序开始查询,直到字符串的的开头,str.lastIndexOf(substr,pos):

let a = `abcdefg`
console.log(a.lastIndexOf('e')); // 4
console.log(a.lastIndexOf('h')); // -1

这里虽然是从后往前找,但是下标也是从头开始的。

(五)includes、startsWith、endsWith

(1)includes()判断字符串是否包含指定的子字符串,找到则返回true,否则返回false(这种方法区分大小写)。

let a = `How do you do`
console.log(a.includes('you')); // true
console.log(a.includes('YOU')); // false
console.log(a.includes(' ')); // true 这里字符串中包含了空格,所以返回的是true
console.log(a.includes('you',8)); // false 第二个参数是从下标多少开始

(2)startsWith(判断字符串是不是以什么开头)和endsWith(判断字符串是不是以什么结尾),区分大小写

let a = `How do you do`
console.log(a.startsWith('How')); // true
console.log(a.startsWith('ow')); // false
console.log(a.startsWith('how')); // false
let a = `How do you do`
console.log(a.endsWith('do')); // true
console.log(a.endsWith('DO')); // false
console.log(a.endsWith('d')); // false

(六)字符串的截取方法

(1)substring(start,stop),截取从两个指定下标之间的字符。(从start开始,到stop结束,不包括stop)

let a = `abcdefghijklmn`
console.log(a.substring(2)); // cdefghijklmn 从下标2开始,到结尾
console.log(a.substring(0,3)); // abc 从下标0开始,到下标2
console.log(a.substring(1,1)); // 空 下标相等为空
console.log(a.substring(2,1)); // b start比stop大,先交换位置
console.log(a.substring(2,-1)); // ab 有一个为负数则先转换成0,然后遵循其他规则
console.log(a.substring(1,2.6)); // b 有小数,则向下取整,然后遵循其他规则
console.log(a.substring(1,-2.6)); // a 有负小数,则直接先转换为0,然后遵循其他规则

(2)substr(start,length),截取从start开始下标的指定长度的字符。(没有标准化,尽量不使用)

let a = `abcdefghijklmn`
console.log(a.substr(2)); // cdefghijklmn 从下标2开始,到结尾
console.log(a.substr(1,5)); // bcdef 从下标1开始,长度为5
console.log(a.substr(-3,2)); // lm start为负数的情况下,从后开始往前数,从1开始数u,例如-1就是字符串中的最后一个字符。
console.log(a.substr(1,-3)); // 空字符串 length长度为负数的话,直接当作0来进行处理,返回""
console.log(a.substr(1.2,3.6)); // bcd 小数的话,向下取整。

(3)slice(start,end),与substring差不多

let a = `abcdefghijklmn`
console.log(a.slice(2)); // cdefghijklmn 从下标2开始,到结束
console.log(a.slice(2,6)); // cdef 从下标2开始,到下标6之间,不包含下标6
console.log(a.slice(2,2)); // 空字符串
console.log(a.slice(2,1)); // 空字符串
console.log(a.slice(2,-1)); // cdefghijklm 从下标2开始,到从右往左数第一个(不包括)
console.log(a.slice(-2,-1)); // m 从右往左数第二个开始,到从右往左数第一个(不包括)