includes()
返回布爾值,表示是否找到了參數字符串es6
let str = "Hello world!";
console.log(str.includes("o")); // true
console.log(str.includes("w")); // true
console.log(str.includes("w", 7)); // false
複製代碼
startsWith()
返回布爾值,表示參數字符串是否在原字符串的頭部正則表達式
let str = "Hello world!";
console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("world")); // false
console.log(str.startsWith("world", 6)); // true
複製代碼
endsWith()
返回布爾值,表示參數字符串是否在原字符串的尾部。ui
let str = "Hello world!";
console.log(str.endsWith("Hello")); // false
console.log(str.endsWith("!")); // true
console.log(str.endsWith(" ", 6)); // true
複製代碼
repeat()
方法返回一個新字符串,表示將原字符串重複n次spa
console.log("x".repeat(3)); // xxx
console.log("hello".repeat(2)); // hellohello
console.log("na".repeat(0)); // ''
// 參數是小數,會被向下取整
console.log("na".repeat(2.9)); // nana
// 參數若是是 Infinity 或者是 負數,會報錯
// console.log("na".repeat(Infinity)); // 報錯
// console.log("na".repeat(-1)); // 報錯
// 0到-1之間的數,NaN,等同於 0
console.log("na".repeat(-0.9)); // ''
console.log("na".repeat(NaN)); // ''
// 參數是字符串,則會先轉換成數字
console.log("na".repeat("na")); // ''
console.log("na".repeat("3")); // nanana
複製代碼
padStart()
字符串補全長度的功能,用於頭部補全3d
console.log("x".padStart(5, "ab")); // ababx
console.log("x".padStart(4, "ab")); // abax
// 若是原字符串的長度,等於或大於最大長度,則字符串補全不生效,返回原字符串
console.log("xxx".padStart(2, "ab")); // xxx
// 若是用來補全的字符串與原字符串,二者的長度之和超過了最大長度,則會截去超出位數的補全字符串。
console.log("abc".padStart(10, "0123456789")); // 0123456abc
// 若是省略第二個參數,默認使用空格補全長度。
console.log("x".padStart(4)); // ' x'
// 常見用途:
// 爲數值補全指定位數
console.log("1".padStart(10, "0")); // 0000000001
console.log("12".padStart(10, "0")); // 0000000012
console.log("123456".padStart(10, "0")); // 0000123456
// 提示字符串格式
console.log("12".padStart(10, "YYYY-MM-DD")); // YYYY-MM-12
console.log("09-12".padStart(10, "YYYY-MM-DD")); // YYYY-09-12
複製代碼
padEnd()
字符串補全長度的功能,用於尾部補全code
console.log("x".padEnd(5, "ab")); // xabab
console.log("x".padEnd(4, "ab")); // xaba
// 若是原字符串的長度,等於或大於最大長度,則字符串補全不生效,返回原字符串
console.log("xxx".padEnd(2, "ab")); // xxx
// 若是用來補全的字符串與原字符串,二者的長度之和超過了最大長度,則會截去超出位數的補全字符串。
console.log("abc".padEnd(10, "0123456789")); // abc0123456
// 若是省略第二個參數,默認使用空格補全長度。
console.log("x".padEnd(4)); // 'x '
複製代碼
trimStart()
消除字符串頭部的空格,返回的是新字符串,不會修改原始字符串ip
trimLeft()
是 trimStart()
的別名let str = ' abc ';
console.log(str.trimStart()); // 'abc '
console.log(str.trimLeft()); // 'abc '
複製代碼
trimEnd()
消除字符串頭部的空格,返回的是新字符串,不會修改原始字符串字符串
trimRight()
是 trimEnd()
的別名let str = ' abc ';
console.log(str.trimEnd()); // ' abc'
console.log(str.trimRight()); // ' abc'
複製代碼
matchAll()
返回一個正則表達式在當前字符串的全部匹配,get