1、我們都知道es5提供了indexOf方法可返回某個指定的字符串值在字符串中首次出現(xiàn)的位置,沒有的話就返回-1,es6又提供了三種新方法,
(1)includes():返回布爾值,表示是否找到了參數(shù)字符串。
(2)startsWith():返回布爾值,表示參數(shù)字符串是否在原字符串的頭部。
(3)endsWith():返回布爾值,表示參數(shù)字符串是否在原字符串的尾部。
這三種方法都支持第二參數(shù),表示從第幾位開始搜索
var w="The world is so big that I want to go out to see it";
console.log(w.indexOf("big",1));//16,第一個參數(shù):要查找的字符串,第二個參數(shù):從哪個位置開始查
console.log(w.includes("big",1));//true,兩個參數(shù)與indexOf一致,返回值為true,false
console.log(w.startsWith("The",0));//true,兩個參數(shù)與indexOf一致,返回值為true,false
console.log(w.startsWith("world",1));//false,因?yàn)閺牡?個位置開始,world字符串不在從第1個位置開始的源字符串的頭部。
console.log(w.startsWith("world",4));//true,因?yàn)閺牡?個位置開始,world字符串在從第4個位置開始的源字符串的頭部。
console.log(w.endsWith("big",19));//true,第一個參數(shù):要查找的字符串,第二個參數(shù):第幾個位置之前的字符串
console.log(w.endsWith("big",19));//表示的是big是否符合位于第19個位置之前的字符串的尾部
2、接下來為大家介紹一個返回字符串的repeat方法,repeat方法類似于函數(shù)調(diào)用,可以在輸出時將原字符串重復(fù)n次。但是因?yàn)閞epeat()方法存在諸多不兼容問題,請諸位慎用
let a="hello ";
console.log(a.repeat(2));//hello hello ,里面的數(shù)字2代表重復(fù)幾次
console.log(a.repeat(3.5));//hello hello hello,重復(fù)三次說明參數(shù)是整數(shù),如果是小數(shù)默認(rèn)向下取整
console.log(a.repeat(-2));//Uncaught RangeError:說明參數(shù)不能為負(fù)數(shù)
console.log(a.repeat(-0.2));//輸出結(jié)果為空說明(-1,0)之間的數(shù)都會變?yōu)?