es6新语法系列,查找字符串,模板字符串

一、模板字符串:

ES6引入了一种新型的字符串字面量语法,我们称之为模板字符串(template strings)。除了使用反撇号字符 ` 代替普通字符串的引号 ' 或 " 外,它们看起来与普通字符串并无二致。在最简单的情况下,它们与普通字符串的表现一致:

拼接字符串时用``,例如:console.log(`用户 ${user.name} 未被授权执行 ${action} 操作。`)

二、for...of字符串的遍历接口

for(let i of "abc"){
    console.log(i);
}
// a
// b
// c
//空格也会被遍历出来

三、includes判断是否包含某字符串,返回布尔值

与indexOf的区别:indexOf返回字符串的下标,找不到则返回-1

        includes返回布尔值,只能判断是否存在

var s = "hello";
// es5
s.indexOf("o"); // 4
// es6
s.includes("o"); // true
s.includes("d"); // false
s.includes("h", 2); // false 从第三个字符开始找

四、startsWith 参数字符串是否在源字符串的头部,返回布尔值

格式:str.startsWith(searchString[, position])

var s = "hello world";
// es5
s.indexOf("hello"); // 0 等于0表示就在源字符串头部
// es6
s.startsWith("hello"); // true
s.startsWith("world"); // false
s.startsWith("world", 6); // true

五、endsWith 跟startsWith相反,表示参数字符串是否在源字符串的尾部,返回布尔值

格式:str.endsWith(searchString[, position])

var s = "hello world";
// es5
String.prototype.endWith=function(endStr){
  var d=this.length-endStr.length;
  return (d>=0&&this.lastIndexOf(endStr)==d)
}
s.endWith("world"); // true
// es6
s.endsWith("world"); // true
s.endsWith("world", 5); // false
s.endsWith("hello", 5); // true

六、repeat 将原字符串重复n次,返回一个新字符串

var s = "s";
s.repeat(3); // sss
s.repeat(2.6); // ss 小数会被取整
s.repeat(-2); // RangeError 报错
s.repeat(0); // ""

七、模板字符串 是增强版的字符串,用反引号(`)标识

它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量,好处相当明显,不用再拼接字符串,使用模板字符串内部可以使用变量了。

// es5 输出模板通常是如下格式,相当繁琐还不方便
var name="Bob",time="today";
var resultStr = "hello "+name+", how are you "+time+'?'; //hello Bob, how are you today?
// es6 模板字符串
console.log(`string text line 1
string text line 2`);
//string text line 1
//string text line 2

// 直接用${变量名}表示
`Hello ${name}, how are you ${time}?` // Hello Bob, how are you today?
// 使用表达式
var obj={a:1,b:2};
`${obj.a+obj.b}` // 3
// 使用函数
function fn() {
  return "Hello World";
}
`this is fn return str: ${fn()}` // this is fn return str: Hello World
原文地址:https://www.cnblogs.com/zsz179248496/p/6817522.html