js字符串方法小结

1.charAt

  • 返回指定位置字符,a.charAt(1)等价于a[1]
var a = "123abc";
console.log(a.charAt(1));//2
console.log(a[1]);//2

2.slice

  • 返回一个子字符串,不改变原字符串
var a = "123abc";
console.log(a.slice(1, 4));//23a
console.log(a.slice(1));//23abc
console.log(a.slice(-5, -1));//23ab

3.substring

  • 与slice方法相似,若第二个参数大于第一个参数,会自动更换两个参数的位置,参数不为负
var a = "123abc";
console.log(a.substring(1, 4));//23a
console.log(a.substring(1));//23abc
console.log(a.substring(4, 1));//23a

4.substr

  • 与slice方法相似,第一个参数为起始位置,第二个参数为截取长度。若第二个参数为负,自动转为0,返回空字符串
var a = "123abc";
console.log(a.substr(1, 4));//23a
console.log(a.substr(1));//23abc
console.log(a.substr(4, 1));//23a
console.log(a.substr(1, -1));//空字符串

5.indexOf

  • 返回查询字符串第一次出现的位置,没有返回-1
var a = "123abc";
console.log(a.indexOf('a'));//3
console.log(a.indexOf("f"));//-1

6.trim

  • 去除字符串两端空格,返回新字符串,不改变原字符串
var a = " 123abc ";
console.log(a);// 123abc 
console.log(a.trim());//123abc

7.toLowerCase

  • 将字符串全部转为小写,返回新字符串,不改变原字符串
var a = "ABCDEFG";
console.log(a.toLowerCase());//abcdefg

8.toUpperCase

  • 将字符串全部转为大写,返回新字符串,不改变原字符串
var a = "abcdefg";
console.log(a.toUpperCase());//ABCDEFG

9.replace

  • 替换匹配的子字符串,一般情况下只替换第一个匹配
var a = "123 abc abc";
console.log(a.replace("abc", "efg"));//123 efg abc

10.split

  • 按照给定规则分割字符串,返回一个由子字符串组成的数组
var a = "1*2*3*a*b*c";
console.log(a.split("*"));//["1", "2", "3", "a", "b", "c"]

11.charCodeAt

  • 返回字符串指定位置的Unicode码点(十进制)
var a = "123abc";
console.log(a.charCodeAt(3));//97

12.fromCharCode

  • 返回码点所表示的字符
console.log(String.fromCharCode(97));//a

13.match

  • 将匹配的结果放入数组中,并返回
var a = "123abc456def";
console.log(a.match(/123/));//["123"]
console.log(a.match(/\d/g));//["1", "2", "3", "4", "5", "6"]

14.search

  • 查找符合正则的字串的位置,只返回第一个匹配的位置
var a = "123abc456def";
console.log(a.search(/\d/));//0
console.log(a.search(/[a-z]/));//3

15.includes

  • 返回布尔值,表示是否找到了参数字符串
var a = "123abc456def";
console.log(a.includes("123"));//true
console.log(a.includes("dfa"));//false

16.startsWith & endsWith

  • 返回布尔值,表示参数字符串是否在原字符串的头部或尾部
var a = "123abc456def";
console.log(a.startsWith("123"));//true
console.log(a.endsWith("deg"));//false

17.repeat

  • 将字符串复制n次
var a = "123abc";
console.log(a.repeat(2));//123abc123abc

18.padStart & padEnd

  • 补全字符串,第一个参数为最小长度(需大于字符串长度),第二个参数为用来补全的字符,若不写第二个参数,默认以空格补全
var a = "123abc";
console.log(a.padStart(9, "+"));//+++123abc
console.log(a.padEnd(9, "-"));//123abc---

你可能感兴趣的:(js字符串方法小结)