本章只整理较为常用的几个方法,用于正则校验的模式匹配方法、字符串比较等本次不进行整理。
一、字符方法
1、charAt():接收一个位置查询的索引值(借用数组的索引说法),以单字符形式返回。
let str = 'hellow world'
alert(str.charAt(1))//e
2、在支持的浏览器中还可以使用方括号加数字索引访问字符串的特定字符
IE8+
let str = 'hellow world'
alert(str[1])//e
二、字符串操作方法
1、concat():传入一个或多个字符串作为参数,将它们拼接起来
原字符串不变
let str1 = 'hello '
let str = str1.concat('world')
alert(str)//hello world
但是一般使用加号+拼接字符串较为常用和简易
2、slice():截取字符串,传入2个参数:开始位置和结束位置(可选),遵循“左闭右开”的规则
- 如果没有传第2个参数,则截取到末尾
let str = 'hello world'
console.log(str.slice(3, 7))//lo w
console.log(str.slice(3))//lo world
- 当第2个参数小于或等于第1个参数时,返回空字符串
let str = 'hello world'
console.log(str.slice(3, 0))//''
console.log(str.slice(3, 3))//''
- 参数传入负值时,会将该值与字符串长度相加
let str = 'hello world'
console.log(str.slice(-3))//rld:等同于slice(8)
console.log(str.slice(3, -4))//lo w:等同于slice(3,7)
3、substr():截取字符串,传入2个参数:开始位置和截取个数(可选)
- 如果没有传第2个参数,则截取到末尾
let str = 'hello world'
console.log(str.substr(3, 7))//lo worl
console.log(str.substr(3))//lo world
- 第1个参数传入负值时,会将该值与字符串长度相加;第2个参数传入负值时,会被转换为0
let str = 'hello world'
console.log(str.substr(-3))//rld:等同于substr(8)
console.log(str.substr(3, -4))//'':等同于substr(3,0)
IE9以下的IE在substr()参数传递负值时,会返回原始的字符串
4、substring():截取字符串,与slice()方法相同,传入2个参数:开始位置和结束位置(可选),遵循“左闭右开”的规则
- 如果没有传第2个参数,则截取到末尾
let str = 'hello world'
console.log(str.substring(3, 7))//lo w
console.log(str.substring(3))//lo world
- 当第2个参数小于第1个参数时,会自动将较小的数作为开始位置,较大的数作为结束位置
let str = 'hello world'
console.log(str.substring(3, 0))//hel
- 参数传入负值时,都会被转换为0
let str = 'hello world'
console.log(str.substring(-3))//hello world:等同于substring(0)
console.log(str.substring(3, -4))//hel:等同于substring(0,3)
三、字符串位置方法
1、indexOf() 和 lastIndexOf():从字符串中查找给定子字符串的位置,方法返回子字符串的位置索引,如果未找到则返回 -1。indexOf() 从开头向后搜索, lastIndexOf()从末尾向前搜索。传入2个参数:
- 第1个参数是要搜索的子字符串
let str = 'hello world'
console.log(str.indexOf('o'))//4
console.log(str.lastIndexOf('o'))//7
console.log(str.indexOf('wo'))//6
console.log(str.indexOf('hw'))//-1
- 第2个参数:开始搜索的位置索引(可选)
let str = 'hello world'
console.log(str.indexOf('o',6))//7
console.log(str.lastIndexOf('o',6))//4
2、trim():删除字符串前后空格,返回结果,并不改变原字符串
let str = ' hello world '
console.log(str.trim())//'hello world'
console.log(str)//' hello world '
四、字符串大小写转换方法
toLowerCase():转换为小写
toUpperCase():转换为大写
toLocaleLowerCase()、toLocaleUpperCase():根据特定地区转换为小/大写
let str = 'hello world'
console.log(str.toUpperCase())//HELLO WORLD
console.log(str.toLocaleUpperCase())//HELLO WORLD
console.log(str.toLowerCase())//hello world
console.log(str.toLocaleLowerCase())//hello world
在不知道自己的代码会在哪种语言环境下运行时,使用针对地区的方法较稳妥。