4>字符串方法

119 阅读2分钟

先加一个es6Number方法判断一个数值是否为整数的方法

Number.isInteger()

Number.isInteger(10)    // true
Number.isInteger(10.1)    // false

chartAt()

返回索引位的字符

let str = 'dfafd' 
console.log(str.chartAt(2))     //  'a'

String.fromCodePoint(0x1F60A)

😊 此时返回一个笑脸,些方法是返回UTF-16码元创建的字符串字符,可以传入多个,自动拼接成新的字符串

concat()

将一个或多个字符串拼接成一个新字符串,但其实这里使用+号更方便

let str = 'hello '
let str2 = str.concat('word', '!')
console.log(str2)     //  'hello word!'

字符串截取三个方法

1>slice(start, end) 字符串开始的位置到结束的位置 2>substring(start, end) 字符串开始的位置到结束的位置 3>substr(start, num) 字符串开始的位置截取几个数

如果没有第二个参数,那么三个返回的值是一样的,老师从开始位置到末尾

let str = 'hello word'
console.log(str.slice(2, 6) )         //  'llo w'
console.log(str.substring(2, 6) )     //  'llo w'
console.log(str.substring(2, 6) )     //  'llo wo'

字符串找索引方法

1>indexOf() 从开头往后找 2>lastIndexOf() 从尾部往前找 如果找不到返回 -1,可以传入第二个参数,表示开始搜索的位置开始查找

let str = 'hello word'
console.log(str.indexOf('o') )         //  4
console.log(str.lastIndexOf('o') )     //  7

console.log(str.indexOf('o'6) )         //  7
console.log(str.lastIndexOf('o'6) )     //  4

trim()

字符串去掉前后空格

let str = '   hello word   '
console.log(str.trim())         //  'hello word'

repeat(num)

接收一个参数,表示将这个字符串重复多少次

let str = 'hello '
console.log(str.repeat(3))         //  'hello hello hello'

repeat(num)

接收一个参数,表示将这个字符串重复多少次

let str = 'hello '
console.log(str.repeat(3))         //  'hello hello hello'

padStart(idx,str) , padEnd(idx, str)

接收2个参数,表示将这个字符串在开头或者结尾拼接str到idx长度,会自动重复并截断str

let str = 'hello '
console.log(str.padStart(6, 'word'))         //  'whello '
console.log(str.padEnd(6, 'word'))         //  'hello w'

字符串原型上暴露了一个@@iterator方法,表示可以迭代每个字符,可以用来解构

let str = 'hello '
console.log([...str])         //  ['h', 'e', 'l', 'l', 'o', ' ']

字符串大小转换

1> toLowerCase() 2> toUpperCase()

let str = 'hello word'
let str2 = 'HELLO WORD'
console.log(str2.toLowerCase())         //  'hello word'
console.log(str.toUpperCase())          //  'HELLO WORD'

replace()

字符串替换,接收两个参数,第一个参数为字符串或者RegExp对象

let str = 'hello hello'
console.log(str.replace('e','o'))    // 'hollo hello'  只会替换第一个匹配的字符
console.log(str.replace(/e/g,'o'))    // 'hollo hollo'  将所有的e替换为o

split()

字符串替换,接收两个参数,第一个参数为字符串或者RegExp对象

let str = 'hello hello'
console.log(str.replace('e','o'))    // 'hollo hello'  只会替换第一个匹配的字符
console.log(str.replace(/e/g,'o'))    // 'hollo hollo'  将所有的e替换为o

match()

获取字符串中的数字

let str = 'hello555 hello777 888oo'
console.log(str.match(/\d+/g))    // ['555', '777', '888']  获得字符串数组