字符串方法总结三(已完结)

177 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天,点击查看活动详情

整理字符串中常用的方法......

padStart方法——将字符串扩展到指定的长度

  1. 作用:将字符串扩展到指定的长度,如果长度不够,那么在字符串左侧以指定字符补位
  2. 格式:str.padStart(长度,'用来补位的字符');
        var str = 'abcdef';
        var res = str.padStart(10, '*');
        console.log(res); // ****abcdef

padEnd方法——将字符串的长度进行扩展

  1. 作用:将字符串的长度进行扩展,如果长度不够,在字符串的末尾用指定字符补位
  2. 格式:str.padEnd(长度,'指定字符');
        var str = 'abcdef';
        var res = str.padEnd(10, '-');
        console.log(res); // abcdef----

注意:如果指定的长度小于字符串现有长度,那么不需要补位,直接范围字符串本身。

        var str = 'abcdef';
        var res = str.padStart(3, '*');
        console.log(res); // abcdef

toFixed方法

  1. 作用:对数据进行小数位数的保留
  2. 格式:数据.toFixed(小数位数);
  3. 返回值:返回值为字符串类型
        var num = Math.PI;
        console.log(typeof num.toFixed(1)); // string

字符串的编码与解码方法

1.btoa方法

  1. 作用:按照Base64的编码方式,对字符串进行编码
  2. 格式:btoa(str);

2.atob方法

  1. 作用:将按照Base64编码方式得到的字符串解码回原有的字符串
  2. 格式:atob(str);
        var str = 'helloworld';

        // 按照Base64编码方式进行编码
        var res = btoa(str); 
        console.log(res);//aGVsbG93b3JsZA==
        
        // 利用atob方法进行解码
        var res2 = atob(res);
        console.log(res2); // helloworld

3.encodeURIComponent方法

  1. 作用:对字符串进行编码,常用于对query string进行编码
  2. 格式:encodeURIComponent(str);

4.decodeuURIComponent方法

  1. 作用:对字符串进行解码
  2. 格式:decodeURIComponent(str);
        var str = '?name=张三&age=10&gender=男';
        // 利用encodeURIComponent方法对字符串str进行编码
        var res = encodeURIComponent(str);
        console.log(res); // %3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D10%26gender%3D%E7%94%B7
        
        // 利用decodeURIComponent方法对字符串进行解码
        var res2 = decodeURIComponent(res);
        console.log(res2); // ?name=张三&age=10&gender=男

补充—— try catch:异常捕获机制

  1. 作用:如果没有try catch,那么当程序中有错误时,程序就会停到错误的位置,不在继续往下执行,即使后面的代码是正确的,也不执行,那么这样的用户体验不好,所以我们可以使用try catch异常捕获机制,将可能有问题的代码放在try中,然后将解决的方式放在catch中。这样就算程序发现错误,程序也会继续执行后面的代码
  2. 格式
            try {
                可能会有问题的代码
            } catch (error) {
                错误的处理方式
            }
        try {
            var arr = new Array(-10);
            console.log(arr);
        } catch (error) {
            console.log(error); // RangeError: Invalid array length at <anonymous>:2:23
        }