JS 常见的操作字符串

  1. 字符串常用方法
    charAt() 返回指定索引的位置的字符,索引从0开始。
    concat() 将两个或多个字符串拼接,返回新字符串。
    indexof() 查找字符串下标,找不到则返回-1 ,用法同search()。
    match() 返回正则表达式模式对字符串进行查找,返回查找结果。
    replace(a,b)  将字符串a 替换成 b。
    search() 指明是否存在相应的匹配。如果找到,返回一个整数值,指明偏移位置。如果找不到匹配,返回 -1。
    slice(start,end)  提取字符串的一部分,返回新字符串,左闭右开。
    split('a',1) 以第一个参数字符拆分,组成一个新数组并返回,第二个参数表示返回数组的元素个数,无第二个参数则返回整个数组。
    substr(start,length)  截取字符串,从start位置开始的 length 个字符(左闭右开)。
    toUpperCase() 
    toLowerCase() 

    trim() 去除字符串两边的空白。
     
  2.  将字符串 foo = "get-element-by-id" 转化成驼峰表示法 “getElementById”.
    function camalCase(msg) {
      let arr = msg.split("-");
      for (let i = 1; i < arr.length; i++) {
        arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substr(1, arr[i].length - 1);
      }
      msg = arr.join("");
      return msg;
    }
    
    let foo = "get-element-by-id";
    console.log(camalCase(foo))
    
    //输出结果:
    //"getElementById"

     

你可能感兴趣的:(JSCool)