ES6中新增的字串方法

2021-09-27 01:56:33 字數 1181 閱讀 3190

1.startswith方法

該方法用於判定字串是否是以指定的字串開頭(其實是具體從某個位置開頭)

// let str = "今天天氣不錯";

// 判定str是否是以"今天"開頭

// let result = str.startswith("今天");

// console.log(result);//true

// 判定 "天氣"是不是從str的下標2開始

// let result1 = str.startswith("天", 1);

// console.log(result1);//true

2.endswith方法

該方法用於判定字串是否是以指定的字串結尾(其實也是從某個具體位置結尾)

// let str = "今天天氣不錯";

// // 判定是否是以"錯"結尾

// let result = str.endswith("錯");

// console.log(result);//true

// // 判定字串的到倒數第二個字是否是以"不"結尾

// let result1 = str.endswith("不", 5);

// console.log(result1);//true

3.includes方法

該方法用於判定字串是否包含另乙個字串

// let str = "今天天氣不錯";

// 判定str中是否包含 "氣" 這個字

// let result = str.includes("氣");

// console.log(result);//true

// 判定str中從下標3開始往後 是否包含"氣"這個字

// let result1 = str.includes("氣", 3);

// console.log(result1);//true

4.repeat方法

該方法用於重複字串,引數是數字,表示重複次數,返回值是重複次數之後的新的字串

// let str = "今天天氣不錯";

// let str1 = str.repeat(20);

// console.log(str1);

es6 新增字串方法

es6新增了4個字串處理的方法 startswith,endswith,includes,repeat。let str lxy 字串是否以某個字元開頭 console.log str.startswith l true console.log str.startswith x false 字串是否以...

ES6中字串string常用的新增方法小結

es6為js新增了很多方法,包括遍歷 查詢 替換等等,可以很簡潔的替換es5中的類似方法,本文不考慮codepointat等不常用方法。for of let str wbiokr for let s of str 結果 w,b,i,o,k,r 由於es5並沒有為js制定字串相關遍歷方法,for of...

ES6字串新增方法

確定乙個字串是否包含在另乙個字串中。方法返回乙個新字串,表示將原字串重複n次。es2017 引入了字串補全長度的功能。如果某個字串不夠指定長度,會在頭部或尾部補全。padstart 用於頭部補全,padend 用於尾部補全。第乙個引數長度 第二個引數補的資料,超過要補的長度就擷取,小於長度就整體補充...