267 String 的扩展方法:模板字符串(解析变量、换行、调用函数),startsWith(),endsWith(),repeat()

模板字符串(★★★)

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

let name = `zhangsan`;

模板字符串中可以解析变量
let name = '张三'; 
let sayHello = `hello,my name is ${name}`; // hello, my name is zhangsan

模板字符串中可以换行
 let result = { 
     name: 'zhangsan', 
     age: 20,
     sex: '男' 
 } 
 let html = ` <div>
     <span>${result.name}</span>
     <span>${result.age}</span>
     <span>${result.sex}</span>
 </div> `;

在模板字符串中可以调用函数
const sayHello = function () { 
    return '哈哈哈哈 追不到我吧 我就是这么强大';
 }; 
 let greet = `${sayHello()} 哈哈哈哈`;
 console.log(greet); // 哈哈哈哈 追不到我吧 我就是这么强大 哈哈哈哈

实例方法:startsWith() 和 endsWith()

  • startsWith():表示参数字符串是否在原字符串的头部,返回布尔值
  • endsWith():表示参数字符串是否在原字符串的尾部,返回布尔值
let str = 'Hello world!';
str.startsWith('Hello') // true 
str.endsWith('!')       // true

实例方法:repeat()

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

'x'.repeat(3)      // "xxx" 
'hello'.repeat(2)  // "hellohello"

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12237091.html