JS-17-字符串常用方法 / 常量注意点

一、在JS中字符串可以看做一个特殊的数组, 所以大部分数组的属性 / 方法字符串都可以使用

1.获取字符串长度 .length

     let str = "abcd";
     console.log(str.length);

2.获取某个字符 [索引] / charAt

     let str = "abcd";
     //let ch = str[1];
     let ch = str.charAt(1);
     console.log(ch);

3.字符串查找 indexOf / lastIndexOf / includes

      let str = "vavcd";
      //let index = str.indexOf("v");
      let index = str.lastIndexOf("v");
      console.log(index);
      let result = str.includes("p");
      console.log(result);

4.拼接字符串 concat / +

      let str1 = "www";
      let str2 = "it666";
     // let str = str1 + str2; // 推荐
      let str = str1.concat(str2);
      console.log(str);

5.截取子串 slice / substring / substr

     let str = "abcdef";
    // let subStr = str.slice(1, 3);
     let subStr = str.substring(1, 3);  // 推荐,包头不包尾,即截取索引为1,2的值;
     // let subStr = str.substr(1, 3);  // 这里的(1,3)表示从索引为1开始截取3个数;
     console.log(subStr);

1.字符串切割

 let arr = [1, 3, 5];
 let str = arr.join("-");
 console.log(str);
 let str = "1-3-5";
 let arr = str.split("-");
 console.log(arr);

2.判断是否以指定字符串开头 ES6

 let str = "http://www.it666.com";
 let result = str.startsWith("www");
 console.log(result);

3.判断是否以指定字符串结尾 ES6

let str = "lnj.jpg";
let result = str.endsWith("png");
console.log(result);

4.字符串模板 ES6

  let name = "abc";
  let age = 22;
        // let str = "我的名字是" + name + ",我的年龄是" + age;
  let str = `我的名字是${name},我的年龄是${age}`;  //这里字符串前后用 ` ` 包括起来了;
        console.log(str);

二、常量的特点和注意点

常量是不能被修改的,每次修改或者拼接都是生成一个新的;

     let str = "abc";
     // str[1] = "m";
     let newStr = str.replace("b", "m");   // 提供的修改方法,实则是替换;以前的不变,在以前的基础上替换后产生一个新的值;
     

1.基本类型特点
没有属性和方法

2.对象类型的特点
有属性和方法

3.以前之所以能够访问基本数据类型的属性和方法(如.length, replace), 是因为在运行的时候系统自动将基本数据类型包装成了对象类型;


-End

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值