检索字符串时候包含特定序列
- indexOf 该方法是字符串中最常用的,一般使用在判断情况下:查找字符串首次出现的位置,如果找到则返回该字符串的下标值,下标从0开始查找,找不到返回-1.
indexOf(“searchValue”, fromIndex)
searchValue是要查找的字符串;fromIndex是选填项,表示从那个下标值开始查找
例如:
let str = 'hello world'
console.log(str.indexOf('w')) //6
console.log(str.indexOf('w', 7)) //-1
- search().和indexOf()一模一样
- lastIndexOf查找字符串最后出现的位置,查找到返回下标值,找不到返回-1
let str = 'hello worldw'
console.log(str.lastIndexOf('w')) // 13
console.log(str.lastIndexOf('w',7)) // 4
- includes(). 该方法返回boolean值,查找字符串里有没有该值,第一位参数是要查找到内容,第二位是从哪个参数下标开始查找
let str = 'hello world'
console.log(str.includes('w')) // true
console.log(str.includes('w',7)) // false
console.log(str.includes('s')) // false
- startsWith(). 该方法返回boolean值,查找字符串开头是不是该值。第一位参数是 要查找到内容, 第二位参数是下标。
let str = 'hello world'
console.log(str.startsWith('w')) // false
console.log(str.startsWith('w',6)) // true
console.log(str.startsWith('s')) // false
- endsWith. 该方法返回Boolean值,查找字符串结尾是不是该值。第一位参数是要查找到内容,第二位是从哪个参数下标开始查找。下标必须往后查找一位,如果要找的下标是5,就必须写6
let str = 'hello world'
console.log(str.endsWith('d')) // true
console.log(str.endsWith('w',7)) // true
console.log(str.endsWith('s')) // false
- toLowerCase(). 将字符串转换为小写,不会改变原字符串
- toUpperCase(). 将字符串转换为大写,不会改变原字符串
var str = 'HeLLO'
console.log(str.toLowerCase()) //hello
console.log(str.toUpperCase()) //HELLO
- split(). 该方法将字符串分割为字符串数组,不会改变原字符串
split(separator, limit)
separator:必填项。从该参数指定的地方进行分割string
limit:选填项。该参数可指定返回的数组的最大长度。如果没有设置该参数,则整个字符串都会被分割,不考虑数组长度。
var str = 'hello'
console.log(str.split('')) //['h', 'e', 'l', 'l', 'o']
console.log(str.split('', 2)) //['h', 'e']
- substring(). 该方法用于提取字符串中介于两个指定下标之间的字符。
str.substring(from, to)
from:必填项。一个非负整数,规定要提取的子串的第一个字符在string中的位置
to: 可选项。非负整数。设定为子串结束位置。其中值是结束位置加1。不选填就是默认取到原字符串末尾
var str = 'hello'
console.log(str.substring(1,2)) // e
console.log(str.substring(1)) // ello
- slice(). 提取字符串的某个部分,以新的字符串返回被提取的部分
str.slice(start, end)
start:必选项。要截取片段的起始下标,如果为负,则从尾部开始截取。
end:可选项。要截取片段的结束下标,如果是负,从字符串尾部开始算起的位置
var str = 'hello'
console.log(str.slice(1,2)) // e
console.log(str.slice(-2)) // lo
console.log(str.slice(-2,-1)) // l
- substr().
slice(), substr(), substring() 异同点。
1、数组没有substr(), substring()
2、参数为正是,只有substring会自动调换顺序,slice在第一个参数大雨第二个参数时返回空,substr无所谓,除非给定的第一个参数超出原数据长度才会返回空
3、参数为负时,substring不能为负。slice认为从尾部倒数。substr第一个参数可以为负,第二个是截取个数,不能为负
- replace(). 替换字符串。第一个为要被替换的值,第二个是替换的值,不会改变原字符串。
var str = 'hello'
console.log(str.replace('h','e')) // eello
- match(). 匹配字符串,如果查找到返回一个数组对象,数组对象中有:匹配的值 查找到字符串下标 原字符串内容。找不到返回null
var str = 'hello'
console.log(str.match('l')) // ['l', index: 2, input: 'hello', groups: undefined]
console.log(str.match('s')) // null
- repeat(). 该方法的参数是复制几遍字符串,不改变原字符串,不能为负
var str = 'hello'
console.log(str.repeat(2)) // hellohello