ES6 includes()、startsWith()、endsWith()

112 阅读3分钟

ES6 includes()、startsWith()、endsWith()

ES6 引入了 includes()startsWith()endsWith() 三个字符串方法,用于更方便地检查字符串中是否包含特定子字符串、是否以特定子字符串开头或结尾。这些方法比传统的 indexOf() 更直观和易用。

以下是这三个方法的作用和用法:

  1. includes()

includes() 方法用于检查字符串中是否包含指定的子字符串,返回一个布尔值。

语法:

str.includes(searchString[, position])

参数:

  • searchString:要搜索的子字符串。
  • position(可选):从哪个索引位置开始搜索,默认为 0

返回值:

  • 如果包含子字符串,返回 true;否则返回 false

示例:

const str = 'Hello, world!';

console.log(str.includes('world')); // true
console.log(str.includes('World')); // false(区分大小写)
console.log(str.includes('Hello', 1)); // false(从索引 1 开始搜索)
  1. startsWith()

startsWith() 方法用于检查字符串是否以指定的子字符串开头,返回一个布尔值。

语法:

str.startsWith(searchString[, position])

参数:

  • searchString:要搜索的子字符串。
  • position(可选):从哪个索引位置开始检查,默认为 0

返回值:

  • 如果以子字符串开头,返回 true;否则返回 false

示例:

const str = 'Hello, world!';

console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('world')); // false
console.log(str.startsWith('world', 7)); // true(从索引 7 开始检查)
  1. endsWith()

endsWith() 方法用于检查字符串是否以指定的子字符串结尾,返回一个布尔值。

语法:

str.endsWith(searchString[, length])

参数:

  • searchString:要搜索的子字符串。
  • length(可选):将字符串的前 length 个字符作为检查范围,默认为字符串的长度。

返回值:

  • 如果以子字符串结尾,返回 true;否则返回 false

示例:

const str = 'Hello, world!';

console.log(str.endsWith('world!')); // true
console.log(str.endsWith('world')); // false
console.log(str.endsWith('Hello', 5)); // true(只检查前 5 个字符)
  1. 与传统方法的对比

在 ES6 之前,通常使用 indexOf() 方法来实现类似的功能,但 indexOf() 的语义不够直观。

示例:传统方法 vs ES6 方法

const str = 'Hello, world!';

// 检查是否包含子字符串
console.log(str.indexOf('world') !== -1); // true
console.log(str.includes('world')); // true

// 检查是否以子字符串开头
console.log(str.indexOf('Hello') === 0); // true
console.log(str.startsWith('Hello')); // true

// 检查是否以子字符串结尾
console.log(str.lastIndexOf('world!') === str.length - 'world!'.length); // true
console.log(str.endsWith('world!')); // true
  1. 应用场景
  • includes()
    • 检查字符串中是否包含某个关键词。
    • 替代 indexOf() 的常见用法。

示例:

const sentence = 'The quick brown fox jumps over the lazy dog';
console.log(sentence.includes('fox')); // true
  • startsWith()
    • 检查 URL 是否以特定协议开头(如 https://)。
    • 检查文件名是否以特定前缀开头。

示例:

const url = 'https://example.com';
console.log(url.startsWith('https://')); // true
  • endsWith()
    • 检查文件名是否以特定后缀结尾(如 .js)。
    • 检查字符串是否以特定标点符号结尾。

示例:

const filename = 'app.js';
console.log(filename.endsWith('.js')); // true
  1. 注意事项
  • 区分大小写:这三个方法都是区分大小写的。
  • 参数类型:如果传入的参数不是字符串,会被隐式转换为字符串。
  • 兼容性:这些方法在 ES6 中引入,不支持 IE 浏览器。

总结

includes()startsWith()endsWith() 是 ES6 引入的三个实用的字符串方法,它们的作用分别是:

  • includes():检查字符串是否包含子字符串。
  • startsWith():检查字符串是否以子字符串开头。
  • endsWith():检查字符串是否以子字符串结尾。

这些方法比传统的 indexOf() 更直观和易用,适合用于字符串的常见检查操作。在实际开发中,应根据需求选择合适的方法来简化代码。

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github