函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块,可复用性好,又有利于开发,下面介绍一下字符串常用的官方函数。
1.charAt(num)
返回字符串中某个下标的字符(下标和数组中的下标一致,空格也算字符)
参数 num(下标)
var str = 'hello word'
console.log(str.charAt(1)) // h
2.charCodeAt(num)
获得字符串中某个下标的字符的编码
参数 num(下标)
var str = 'hello word'
console.log(str.charCodeAt(1)) // 101
3.split(分隔符)
根据分隔符将字符串拆分成数组
参数 分隔符
返回值 数组
var str = '2020-3-18'
console.log(str.split('-')) //["2020", "3", "18"]
4.substring(start,end)
用来截取字符串 ,参数下标左闭右开
参数 1.起始下标 (0和正整数) 2.结束下标(可选参数)
返回值 截取的结果字符串
var str = 'hello word'
console.log(str.substring(3)) //lo word
console.log(str.substring(3,8)) //lo wo
5.substr(strat,length)
用来截取字符串的内容
参数 1.起始下标 2.截取长度(可选参数)
返回值 截取的字符串
var str = 'hello word'
console.log(str.substr(3)) //lo word
console.log(str.substr(3,5)) //lo wo
6.toUpperCase() 转换成大写
参数 无
返回值 转成大写的字符串
var str = 'hello word'
console.log(str.toUpperCase()) //HOLLE WORD
7.toLowerCase() 转换成小写
参数 无
返回值 转成小写的字符串
var str = 'HOLLE WORD'
console.log(str.toLowerCase()) //hello word
8.slice() 截取字符串的方法,如果为负数,从后往前截取,包括开始的索引
参数 1.起始下标 (可以是负数) 2.终止下标(可选参数)
var str = 'hello word'
console.log(str.slice(2)) //llo word
console.log(str.slice(2,8)) //llo wo
console.log(str.slice(-4)) //word
console.log(str.slice(-7,-2)) //lo wo
console.log(str.slice(2,-2)) //llo wo
9.indexOf() 查找子串在主串中的第一个出现下标
参数 1.要查找的 2.子串索引起始下标(可选)
返回值 下标(如果找不到返回 -1 )
var str = 'hello word'
console.log(str.indexOf('o')) //4
console.log(str.indexOf('o',6)) //7 从下标6往后找 'o',
console.log(str.indexOf('g',7)) //-1
10.lastIndexOf() 查找元素最后一次出现的位置
参数 1. 要查找的子串
2.下标(可选)
返回值 下标(如果找不到返回 -1 )
var str = 'hello word'
console.log(str.lastIndexOf('o')) //7
console.log(str.lastIndexOf('o',5)) //4 在下标0 至5查找
11.concat() 方法用于连接两个或多个字符串
参数 若干个字符串
返回值 拼接好的字符串
//concat()
var str = 'how'
var t = str.concat(' are')
t = t.concat(' you')
console.log(t) //how are you