字符串相关方法

132 阅读2分钟

JavaScript字符串用于储存和处理文本,可以储存一系列字符。字符串可以插入到引号中的任何字符。所有带单引号或双引号的叫做字符串。

字符串的数据类型:字符串既是基本数据类型,又是复合数据类型

  • 获取字符串中某位字符 charAt()    [] === charAt

    let str = 'abcdefg';
    console.log(str[0])  //"a"
    console.log(str.charAt(1); //"b"
    
  • 获取字符串长度   str.length

    let str = "abcdefg";
    console.log(str.length); //7
    console.log(str[str.length-1]); //"g"
    
  • 查找某个字符,有则返回第一次匹配到的位置,否则返回-1.   indexOf()

    let str = "abcdefg";
    console.log(str.indexOf("a"); //0
    console.log(str.indexOf("z"); //-1
    
  • 将字符转换为ascll码值以及将ascll码值转换为字符  charCodeAt()、String.fromCharCode()

    let str = "abcdefg";
    console.log(str.charCodeAt(0)); //"a"--> 97
    console.log(String.fromCharCode(97)); //97--> "a"
    
  • 字符串拼接      concat(

    let str = "abc";
    console.log(str.concat("efg")); //"abcefg"
    console.log(str.concat("efg","hijk")); //"abcefghijk"
    
  • 字符串切割     slice()    substring()   substr()

    //slice
    let str="abcdefg";
    console.log(str.slice(1,6))  //"bcdef"
    console.log(str.slice(1))    //"bcdefg"
    console.log(str.slice())     //"abcdefg"
    console.log(str.slice(-2))   //"fg"
    console.log(str.slice(6,1))  //""
    /* slice只传两个值个值,则表示左闭右开,不包括结束位置的值
    传入一个值,则表示,从起始位置开始到最后
    不传值则切割整个字符串
    也可以传入负数,字符串倒数第一位为-1 */
    
    //substring()
    let str= "abcdefg";
    console.log(str.substring(1,6)); //"bcdef"
    console.log(str.substring(1));   //"bcdefg"
    console.log(str.substring());    //"abcdefg"
    console.log(str.substring(6,1))  //"bcdef"
    console.log(str.substring(-1))   //"abcdefg"
    /* 用法和slice基本相同,只不过substring,传入的第一个值比第二个值大时,默认会进行从小到大值
    的处理  以及传入负数,会切割整个字符串  */
    
    //substr()
    let str = "abcdefg";
    console.log(str.substr(1,6)  //"bcdef"
    console.log(str.substr(1))   //"bcdefg"
    console.log(str.substr())    //"abcdefg"
    console.log(str.substr(-1))  //"g"
    /* substr 第一个参数表示开始切割的起始位置
     第二个参数表示切割的长度
     传一个值和不传值的表现和slice相同
     也可以传入负值 
     */ 
    
  • 字符串转换大小写    toUpperCase()   toLowerCase()

    let str = "adABDndj";
    console.log(str.toUpperCase());  //"ADABDNDJ"
    console.log(str.toLowerCase());  //"adabdndj"
    
  • 切割字符串返回数组   split()

    let str = "abcdefg"
    console.log(str.split(""))   //a,b,c,d,e,f,g
    console.log(str.split("",3)) //a,b,c
    
  • 移除字符串首尾空白    trim()

    let str = " abcd";
    console.log(str.trim())   //"abcd"