js中字符串方法
分类:javascript
1、charAt
用来获取字符串中指定位置的字符
let str = "hello"
console.log(str.charAt(3)) // l
console.log(str.charAt(1)) // e
2、字符串查找
1) indexOf
判断指定字符是否在字符串中,从前往后查找,如果存在,则返回第一次出现的位置,否则返回 -1
indexOf(指定字符, 开始查找的位置)
let str = "hello word"
console.log(str.indexOf("a")) // -1
console.log(str.indexOf("o")) // 4
console.log(str.indexOf("o", 5)) // 7
2) lastIndexOf
用法和indexOf一样,不同点:lastIndexOf是从后往前找
let str = "hello word"
console.log(str.lastIndexOf("o")) // 7
console.log(str.lastIndexOf("o", 5)) // 4
3、字符串截取
1) substr
按个数截取,substr(开始截取的位置, 截取字符的个数)
如果没有第二个参数,表示截取到最后
let str = "hellowordygh";
console.log(str.substr(4)); // owordygh
console.log(str.substr(5, 2)); // wo
2) substring
按位置截取,substring(start, end) 截取的是从start到end-1的字符
let str = "hellowordygh";
console.log(str.substring(0, 2)) // he
console.log(str.substring(3, 6)) // low
4、字符串大小写转换
1) toUpperCase
转换成大写
let str = "hello";
console.log(str.toUpperCase()) // HELLO
2) toLowerCase
转换成小写
let str = "HELLO";
console.log(str.toLowerCase()) // hello
5、split
字符串分割,将字符串分割成数组
split(指定分割字符, 指定数组长度),第一个参数可以是正则
let str = "hello"
console.log(str.split("")) // ["h", "e", "l", "l", "o"]
let str2 = "one,two,three,four"
console.log(str2.split(",")) // ["one", "two", "three", "four"]
let str3 = "one66two66three66four"
console.log(str3.split("66", 3)) // ["one", "two", "three"]
let str4 = "one63two56three96four"
let str4Reg = /\d{2}/
console.log(str4.split(str4Reg)) // ["one", "two", "three", "four"]
6、concat
字符串拼接
将两个或多个字符串拼接成一个字符串
let str1 = "zfcOne"
let str2 = "zfcTwo"
let str3 = "zfcThree"
console.log(str1.concat()) // zfcOne
console.log(str1.concat(str2)) // zfcOnezfcTwo
console.log(str1.concat(str2,str3)) // zfcOnezfcTwozfcThree
7、trim
删除字符串首尾的空格
let str = " hello word "
console.log("[" + str + "]") // [ hello word ]
console.log("[" + str.trim() + "]") // [hello word]
8、replace
字符串替换。
接受两个参数,第一个可以是正则表达式,第二个可以是函数
把第一个参数拿到字符串中去搜索,匹配上了就用第二个参数去替换
如果第一个参数是字符串,那么只会替换第一个匹配项
let str = "hello66word66 "
console.log(str.replace(66, 99)) // hello99word66
console.log(str.replace(/\d{2}/g, 99)) // hello99word99
let str2 = "1234"
let str3 = str2.replace(/\d/g, (i) => {
// i 代表字符串中的每个字符
return Number(i) * 2
})
console.log(str3) // 2468
9、search
字符串搜索
只接受一个参数,可以是正则表达式
indexOf只能传入固定的值,search里可以接受正则表达式。
匹配子字符串或正则是否在字符串中, 如果匹配上, 则返回具体的位置, 否则返回-1
let str = 'ddadfhkm'
console.log(str.search('a')) // 2
console.log(str.search('b')) // -1
let str2 = 'dfgfgsa1234jk8'
console.log(str2.search(/a\d+/))// 6
10、match
匹配上就返回内容,匹配不上就返回null。
只接受一个参数,可以是正则表达式
let str = "dhjkj234lk"
console.log(str.match(234)) // ["234", index: 5, input: "dhjkj234lk", groups: undefined]
console.log(str.match("a")) // null
console.log(str.match(/\d/g)) // ["2", "3", "4"]
一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu