推荐答案
// www.javascriptcn.com code example
const str = "Hello, world!";
// includes: 判断字符串是否包含指定的子字符串
console.log(str.includes("world")); // true
console.log(str.includes("foo")); // false
// startsWith: 判断字符串是否以指定的子字符串开头
console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("world")); // false
// endsWith: 判断字符串是否以指定的子字符串结尾
console.log(str.endsWith("world!")); // true
console.log(str.endsWith("Hello")); // false
// repeat: 将字符串重复指定的次数
console.log(str.repeat(2)); // "Hello, world!Hello, world!"本题详细解读
includes 方法
- 功能: 用于判断一个字符串是否包含另一个字符串。
- 语法:
str.includes(searchString[, position])
searchString: 要搜索的子字符串。
position (可选): 从该位置开始搜索,默认为 0。
- 返回值: 如果包含则返回
true,否则返回 false。
startsWith 方法
- 功能: 用于判断一个字符串是否以指定的子字符串开头。
- 语法:
str.startsWith(searchString[, position])
searchString: 要搜索的子字符串。
position (可选): 从该位置开始搜索,默认为 0。
- 返回值: 如果以指定子字符串开头则返回
true,否则返回 false。
endsWith 方法
- 功能: 用于判断一个字符串是否以指定的子字符串结尾。
- 语法:
str.endsWith(searchString[, length])
searchString: 要搜索的子字符串。
length (可选): 作为字符串的长度,默认为原字符串的长度。
- 返回值: 如果以指定子字符串结尾则返回
true,否则返回 false。
repeat 方法
- 功能: 用于将字符串重复指定的次数。
- 语法:
str.repeat(count)
- 返回值: 返回重复后的新字符串。