我们都知道在 ES6 之前,我们只能使用 indexOf 来判断字符串是否存在某个字符,现在 ES6 多出了几个比较常用的方法:
includes()
:返回布尔值,判断是否找到参数字符串。startsWith()
:返回布尔值,判断参数字符串是否在原字符串的头部。endsWith()
:返回布尔值,判断参数字符串是否在原字符串的尾部。let str = "Ken,KenNaNa,haha"
str.includes("Ken"); // true
str.startsWith("Ken"); // true
str.endsWith("Ken"); // false
str.startsWith("Ken",6) // false
比较常用的,应该就是使用 padStart
console.log("123".padStart(10,"0")); // "0000000123"
模板字符串相当于加强版的字符串,用反引号 `, 除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式。
let string = `Hello'\n'world`;
console.log(string);
// "Hello'
// 'world"
let string1 = `Hey,
can you stop angry now?`;
console.log(string1);
// Hey,
// can you stop angry now?
变量名写在 \{} 中,{} 中可以放入 JavaScript 表达式。
let name = "Mike";
let age = 27;
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info);
// My Name is Mike,I am 28 years old next year.
function f(){
return "have fun!";
}
let string2= `Game start,${f()}`;
console.log(string2); // Game start,have fun!