你都知道的String字符串方法

326 阅读2分钟

string() 字符串相关方法

  • length 返回字符串长度
var str = "hello world";
console.log(str.length); //获取字符串长度 11
  • charAt()
    • 返回字符串中指定位置的字符
console.log(str.charAt(8)); //r
console.log(str[8]); //r
  • charCodeAt()
    • 返回字符串中指定位置的字符的 Unicode 编码
console.log(str.charCodeAt(8)); //114
  • fromCharCode()
    • 根据字符编码获取字符
    • 用法:String.fromCharCode();
res = String.fromCharCode(114);
console.log(res); //r
  • concat()
    • 连接字符串
let res = str.concat(" 你好", "再见");
console.log(res); //hello world 你好再见
  • indexOf()
    • 该方法可以检索一个字符串中是否含有指定内容
    • 如果字符串中含有该内容,返回第一次出现的索引位置
    let str = "hello world";
    let res = str.indexOf("h");
    console.log(res); //0
    
    • 如果字符串中没有该内容,返回-1
let res = str.indexOf("p");
console.log(res); //-1
  • 可以指定第二个参数,指定开始查找的位置
let str = "hellpo world";
let res = str.indexOf("p", 6);
console.log(res); //-1
  • lastIndexOf()
    • 从后往前找
    • 同样有第二个参数,没有返回-1
let str = "hello world";
let res = str.lastIndexOf("l");
console.log(res); //9
  • slice()
    • 可以从字符串中截取指定内容
    • 参数:
      • 第一个参数:开始位置
      • 第二个参数:结束位置,省略表示指定位置到最后
    • 负数,倒数 -1 表示最后一个
    • 左闭右开
let str = "abcdefghigklmn";
let res = str.slice(0, 2);
console.log(res); //ab
  • substring()
    • 可以用来截取一个字符串,与 slice()类似
    • 参数:
      • 第一个参数:开始位置,包括
      • 第二个参数:结束位置,省略表示指定位置到最后
    • 这个方法不能接受负数,写负数和写 0 没啥区别,如果第二个参数小于第二个参数,自动交换位置
let res = str.substring(1, -1);
console.log(res); //a
  • substr()
    • 用来截取字符串
    • 参数:
      • 第一个参数:开始位置
      • 第二个参数:截取长度
let str = "abcdefghigklmn";
let res = str.substr(2, 2);
console.log(res); //cd
  • split()
    • 可以将一个字符串拆分为一个数组
    • 参数:
      • 需要一个字符串作为参数,根据这个参数拆分数组
    • 如果传递一个空串,将每一个字符都转换为数组
let str = "a,b,c,d,e";
let res = str.split(",");
console.log(Array.isArray(res)); //true
console.log(res); //[ 'a', 'b', 'c', 'd', 'e' ]
  • toUpperCase()
    • 将一个字符串转化为大写
  • toLowerCase()
    • 将一个字符串转换为小写
let str = "abcdefg";
let res = str.toUpperCase();
console.log(res); //ABCDEFG

let lowRes = res.toLowerCase();
console.log(lowRes); //abcdefg