在ES5中,能够使用 indexOf
方法和 lastIndexOf
方法查找字符串:spa
let str = 'hello world'; alert(str.indexOf('o')); // 4 alert(str.lastIndexOf('o')); // 7 alert(str.lastIndexOf('z')); // -1
ES6中,又新增了3个方法用于特定字符的查找。code
一、includes()字符串
该方法传入一个字符串参数,而后返回一个布尔值,表示是否在指定字符串中找到了该字符串片断。it
let str = 'hello'; console.log(str.includes('h')); // true console.log(str.includes('z')); // false
二、startsWith()console
该方法传入一个字符串参数,而后返回一个布尔值,表示是否在指定字符串开头找到了该字符串片断。ast
let str = 'hello'; console.log(str.startsWith('h')); // true console.log(str.startsWith('lo')); // false
三、endsWith()模板
该方法传入一个字符串参数,而后返回一个布尔值,表示是否在指定字符串末尾找到了该字符串片断。变量
let str = 'hello'; console.log(str.endsWith('h')); // false console.log(str.endsWith('o')); // true
一、repeat()方法
对一个字符串进行重复,返回一个新字符串。error
let str = 'ha';
console.log(str.repeat(3)); 'hahaha'
参数若是是小数,会被向下取整进行操做。
let str = 'ha';
console.log(str.repeat(2.9)); 'haha'
参数若是是负数,会报错。
let str = 'ha'; console.log(str.repeat(-2)); // error
ES6引入了模板字符串,用反引号标识( `
),主要功能有俩个。
一、定义多行字符串。
let str = `hello hello hello`; console.log(str) // hello // hello // hello
二、在字符中嵌入变量,把变量包裹在 ${}
中便可。
var username = 'tom'; alert(`hello ${username}`); // hello tom