ES6有关String的拓展方法

一、模板字符串

1)定义

为ES6新增的创建字符串的方式,使用反引号``定义

2)特点

模板字符串中可以解析变量

<script>
    let name = `张三`;
//可以解析变量 let sayHello
= `sayhell0,my name is ${name}`; console.log(sayHello); </script>

模板字符串可以换行,即当模板字符串的内容比较对的时候,其显示效果是比较好的

<script>
    let person = {
        name: '张三',
        age: 20
    }
//可以换行 let html
= ` <div> <span>${person.name}</span> <span>${person.age}</span> </div> `; console.log(html); </script>

 

 在模板字符串中可以调用函数,字符串里调用函数的位置将显示函数的返回值

<script>
    const sayHello = function() {
        return "hello,my name is"
    }
//可以调用函数 let greet
= `${sayHello()}张三`; console.log(greet); </script>

 

 二、startWith()和endsWith方法

  作用 返回值
startsWith 表示参数字符串是否在原字符串的头部 布尔值
endsWith 表示参数字符串是否在原字符串的尾部 布尔值

 

<script>
    let str = 'hello world!'
    console.log(str.startsWith('Hello')); //false
    console.log(str.startsWith('hello'));//true
    console.log(str.endsWith('!'));//true
</script>

三、repeat()方法

repeat()方法表示将原字符串重复n次,返回一个新的字符串

<script>
    console.log('hello'.repeat(2)); //hellohello,表示将hello这个字符串重复2次
    console.log('x'.repeat(3)); //xxx,表示把x这个字符串重复三次
</script>

 

posted @ 2021-07-22 10:14  蛋蛋仔  阅读(117)  评论(0编辑  收藏  举报