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