js--字符串方法

300 阅读3分钟

复制与截取

substr(n,m)

  • 作用:从索引n处开始截取m个,如不填写m 直接截取到末尾.如果n,m都不写直接复制全部字符串
  • 参数: n 截取字符串的索引位置, m 截取个数
  • 返回值: 截取过的字符串
let a = "学习技术跳槽涨薪";
let b = a.substr(6,2);
console.log(a,b);// 学习技术跳槽涨薪 涨薪
let c = substr();
console.log(c); // 什么都不传 直接从开头截取到末尾

substring(n,m)

  • 作用:从索引n处开始截取. 截取到索引m, 不包含m. 如不填写m 直接截取到末尾.如果n,m都不写直接复制全部字符串
  • 参数: n 截取字符串的索引位置, m 截取到索引的位置
  • 返回值: 截取过的字符串
let a = "学习技术跳槽涨薪";
let b = a.substring(6, 8); 
console.log(a, b);// 学习技术跳槽涨薪 涨薪
let c = a.substring();
console.log(c); // 什么都不传 直接从开头截取到末尾

concat()拼接

  • 作用: 拼接字符串
  • 参数: 需要拼接的字符串
  • 返回值: 拼接好的字符串
let a = "a,b,c,d";
let b = a.concat(",e,f,g");
console.log(b); // "a,b,c,d,e,f,g"

转换大小写

大写转小写 toLowerCase()

  • 作用: 把大写字母转为小写字母
  • 参数: 无
  • 返回值: 转为小写的字母
let a = "A,B,C,D";
let b = a.toLowerCase();
console.log(a,b); // A,B,C,D a,b,c,d

小写转大写 toUpperCase()

  • 作用: 把大写字母转为小写字母
  • 参数: 无
  • 返回值: 转换后的大写字母
let a = "a,b,c,d";
let b = a.toUpperCase();
console.log(a,b); // a,b,c,d A,B,C,D

获取字符在字符串中出现的位置 indexOf

  • 作用: 获取字符在字符串中出现的位置
  • 参数: 需要查找的字符
  • 返回值: 需要查找的字符首次在字符串中索引的,如果没有返回 -1
<!--let a = "a,b,c,d"; // c 是 4-->
let a = "abcd"; // c 是2
let b = a.indexOf('c');
let C = a.indexOf('F');
console.log(a,b,C); // a,b,c,d/ 2 / -1

lastIndexOf()

  • 作用: 查找字符在字符串中最后一次出现的位置
  • 参数: 需要查找的字符
  • 返回值: 返回字符在字符串中最后一次出现的索引位置,没有就返回-1
<!--let a = "a,b,c,d"; // b = 2-->
let a = "abcdefgb"; // b = 7
let b = a.lastIndexOf('b');
console.log(a,b); // abcdefgb 7

字符串转换 替换

字符串转数组 split()

  • 作用: 按照指定分隔符吧字符串转为数组
  • 参数: 需要指定的分隔符
  • 返回值: 转换后的数组
let a = "a,b,c,d";
let b = a.split(",");
console.log(a,b); // a,b,c,d  ['a', 'b', 'c', 'd'] 

字符串替换 replace(y,x)

  • 作用: 替换字符串对应字符
  • 参数: y = 需要被替换的字符, x = 替换的字符, 如果只填y不填x, 默认将y替换undefined
  • 返回值: 被替换后的字符串
let a = "a,b,c,d"
let b = a.replace("a","六六六");
console.log(a,b)

匹配与查找

match()

  • 作用: 匹配字符串中符合规则的字符并返回匹配字符的数组集合
  • 参数: 需要匹配的字符或者正则
  • 返回值: 符合匹配的字符数组集合 或者不符合返回 null
let a = "a,b,c,d";
let b = a.match("a,b");
console.log(b); // ["a,b"]
let c = a.match("ab");
console.log(c); // null

includes()

  • 作用: 判断字符串中是否存在对应字符
  • 参数: 需要查找的字符
  • 返回值: 有就返回 true 相反就是 false
let a = "a,b,c,d";
let b = a.includes("a");
console.log(b); // true
let c = a.includes("f");
console.log(c); // false