新加了 includes() startsWith() endsWith()三種查找字符串的方法
{
//三種方法都返回一個(gè)boolean值
const s='hello world';
console.log(s.includes('o'));//true
console.log(s.startsWith('hello'));//true
console.log(s.endsWith('world'));//true
console.log(s.endsWith('h'));//false
}
//方法中還可以傳第二個(gè)參數(shù),第二個(gè)參數(shù)代表著從第幾個(gè)下標(biāo)開始查找
{
const s='hello world';
console.log(s.includes('e',6));//false
console.log(s.startsWith('hello',0));//true
console.log(s.endsWith('world',6));//true
}
這三種方法相比較indexOf來說,更加靈活,也方便很多,缺點(diǎn)就是include沒有返回下標(biāo),有人就說了,你這不是廢話嘛,返回下標(biāo)不就是indexOf了,額,,,,,還真是那么回事。。。。。。。
repeat 重復(fù)復(fù)制方法
{
const s='abc';
console.log(s.repeat(3));//abcabcabc
console.log(s.repeat(3.8));//abcabcabc
console.log(s.repeat(0));//''
console.log(s.repeat(-0.8));//''
console.log(s.repeat(-1));//報(bào)錯(cuò)
}
上面的例子可以看出,正整數(shù)按照傳的參數(shù)重復(fù)n出來 小數(shù)取小數(shù)點(diǎn)前的數(shù)重復(fù)n次出來 負(fù)數(shù)報(bào)錯(cuò)
padStart padEnd方法
{
const s='string';
console.log(s.padStart(8,'abcd'));//abstring
console.log(s.padStart(4,'abcd'));//string
console.log(s.padEnd(8,'abcd'));//stringab
console.log(s.padStart(8));// string
console.log('9'.padStart(2,'0'));//09 時(shí)間補(bǔ)零
}
這兩個(gè)方法的第一個(gè)參數(shù),就是要控制字符串的length,第二個(gè)參數(shù)就是要在原有的字符串上加的字符串,padStart就是在原有字符串前面加字符串,padEnd就是在原有字符串后面加字符串,當(dāng)加的字符串加上原有字符串的length大于第一個(gè)參數(shù)時(shí),就會(huì)自動(dòng)把多余的截取掉,如果小于原有字符串的length就會(huì)返回原有的字符串
模板字符串
{
let {a,b,c,d}={a:'張三',b:15,c:'IT',d:function (){return 'show'}}
let [x,y]=[10,3];
const s=`
<ul>
<li class="show">${a}</li>
<li data-index="1">$</li>
<li class="none">${c}</li>
<li class="none">${d()}</li>
<li class="none">${x+y}</li>
</ul>
`;
document.querySelector('body').innerHTML=s;
}
字符串模板真心犀利啊,以前弄個(gè)復(fù)雜點(diǎn)的字符串拼接,那叫一個(gè)費(fèi)勁啊,現(xiàn)在有了字符串模板,真是我大前端的福音啊,兩個(gè)``就搞定了,里面大括號(hào)內(nèi)部可以放入任意的JavaScript表達(dá)式,可以進(jìn)行運(yùn)算,以及引用對(duì)象屬性。
replaceAll 替換字符串中全部相同的字符串
const str=" hello world ";
console.log(str.replaceAll("l",""));// heo word
替換字符串中全部相同的字符串 不會(huì)改變?cè)瓉淼淖址?,返回替換后的字符串
trimStart trimEnd 去除字符串的首尾空白字符
const str=" hello world ";
console.log(str.trimStart());//hello world
console.log(str.trimEnd());// hello world
不會(huì)改變?cè)瓉淼淖址祷靥鎿Q后的字符串
matchAll 為所有匹配的匹配對(duì)象返回一個(gè)迭代器
const str=" hello world ";
let arr=[...str.matchAll(/l/g)];
arr.forEach(item=>{
console.log(item.index);//3 4 10
})
打印結(jié)果,如圖所示

字符串新加的這幾個(gè)方法個(gè)人感覺padStart()和字符串模板是真心大大的有用的,例如時(shí)間倒計(jì)時(shí),你還得對(duì)小時(shí)和分秒補(bǔ)零,有了這個(gè)方法就是小菜一碟了,字符串模板就不用說了,ajax交互局部渲染的時(shí)候,用到那是肯定的
OK,字符串幾個(gè)拓展就簡(jiǎn)單的介紹這幾個(gè),咱們?nèi)f年不變的慣例,如果想學(xué)習(xí)更詳細(xì)的資料請(qǐng)狠狠的點(diǎn)擊這里!