前端提高篇(120):es6模板字符串和字符串拓展

模板字符串

1.传统字符串处理多行字符串时,需要手动添加换行符

let msg = "hellohellohellohellohello\n\
hellohellohellohellohello\n\
hellohellohellohellohellohellohellohellohellohellohello";
console.log(msg);

在这里插入图片描述

2.传统字符串处理字符串包含变量时,需要拼接:

let age = 10;
let msg2 = "hello " + age + " hello";
console.log(msg2); //hello 10 hello

3.es6提出了模板字符串的概念,用反引号来圈起字符串,处理多行字符串时:

let msg1 = `hello
hello
hello`
console.log(msg1);

效果:
在这里插入图片描述
4.模板字符串处理字符串包含变量时,用${},花括号里还可以写表达式

let msg3 = `hello ${age+10} hello`;
console.log(msg3) //hello 20 hello

字符串拓展

1.String.prototype.startsWith
功能:查找字符串A是否以字符/字符串B开头
第一个参数:要匹配的字符B
第二个参数:从源字符串A的哪个位置往后开始找起
返回布尔型,是则返回true;否则返回false

2.String.prototype.endsWith
功能:查找字符串A是否以字符/字符串B结尾
第一个参数:要匹配的字符B
第二个参数:从源字符串A的哪个位置往前(不包含该位置)开始找起
返回布尔型,是则返回true;否则返回false

let msg = "hello";
console.log( msg.startsWith("e",1) ); // true
// 从下标1往后找,包含下标为1的'e'

console.log(msg.endsWith( "ll", 3)); //false
// 从下标3往前找,不包含下标为3的'l',所以不以'll'结尾

3.String.prototype.includes
功能:字符串A是否包含某字符/某字符串B。
第一个参数为:要匹配的字段B;
第二个参数为:从源字符串A的哪个位置开始找起;
返回布尔型,包含则返回true;不包含则返回false

如果用es5来实现这个功能,来增加代码兼容性,用es5的indexOf:

if (!String.prototype.include){
    String.prototype.include = function(search, start){
        if (typeof start !== "number"){
            start = 0;
        }
        if ( start + search.length > this.length){
            return false;
        }else {
            return this.indexOf(search, start) !== -1;
        }
    }
}else {
    String.prototype.include(search, start);
}

4.String.prototype.repeat
功能:重复某字符串
参数:重复次数

let msg = "hello";
console.log(msg.repeat(3)); //输出:hellohellohello
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值