JS字符串包含

JS字符串包含

JS字符串包含

什么是字符串包含

字符串包含是指在JS中判断一个字符串是否包含另一个子字符串的操作。这在日常编程中非常常见,比如我们需要判断一个输入的字符串中是否包含某个关键词,或者我们需要从一个长文本中提取出某段特定的内容等。

ES6的新增方法

在ES6中,新增了一些字符串的方法来更方便地进行字符串包含的判断。

includes()

includes()方法用于判断一个字符串是否包含另一个字符串,返回布尔值。

语法如下:

str.includes(searchString[, position])

参数说明:

  • searchString: 要搜索的子字符串。
  • position(可选): 指定搜索的起始位置,默认为0。

示例代码:

const str = 'Hello, world!';
console.log(str.includes('world')); // true
console.log(str.includes('Hello')); // true
console.log(str.includes('foo')); // false
console.log(str.includes('Hello', 6)); // false

运行结果:

true
true
false
false

startsWith()

startsWith()方法用于判断一个字符串是否以另一个字符串开头,返回布尔值。

语法如下:

str.startsWith(searchString[, position])

参数说明:

  • searchString: 要搜索的子字符串。
  • position(可选): 指定搜索的起始位置,默认为0。

示例代码:

const str = 'Hello, world!';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('world')); // false

运行结果:

true
false

endsWith()

endsWith()方法用于判断一个字符串是否以另一个字符串结尾,返回布尔值。

语法如下:

str.endsWith(searchString[, length])

参数说明:

  • searchString: 要搜索的子字符串。
  • length(可选): 指定搜索的长度,默认为字符串的长度。

示例代码:

const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('Hello')); // false

运行结果:

true
false

indexOf()和lastIndexOf()方法

除了ES6新增的方法,我们还可以使用indexOf()lastIndexOf()方法来判断字符串包含关系。

indexOf()

indexOf()方法用于返回一个字符串在另一个字符串中首次出现的位置,若不存在则返回-1。

语法如下:

str.indexOf(searchValue[, fromIndex])

参数说明:

  • searchValue: 要查找的字符串。
  • fromIndex(可选): 指定开始查找的位置,默认为0。

示例代码:

const str = 'Hello, world!';
console.log(str.indexOf('world')); // 7
console.log(str.indexOf('foo')); // -1
console.log(str.indexOf('Hello', 6)); // -1

运行结果:

7
-1
-1

lastIndexOf()

lastIndexOf()方法和indexOf()类似,不同之处在于它从字符串的末尾开始查找。

语法如下:

str.lastIndexOf(searchValue[, fromIndex])

参数说明:

  • searchValue: 要查找的字符串。
  • fromIndex(可选): 指定开始查找的位置,默认为字符串的长度。

示例代码:

const str = 'Hello, world!';
console.log(str.lastIndexOf('o')); // 8
console.log(str.lastIndexOf('foo')); // -1
console.log(str.lastIndexOf('o', 6)); // 4

运行结果:

8
-1
4

正则表达式

除了上述方法外,我们还可以使用正则表达式来判断字符串包含关系。正则表达式提供了更灵活的匹配模式,使我们能够更精确地进行字符串包含判断。

示例代码:

const str = 'Hello, world!';
const regex = /world/;
console.log(regex.test(str)); // true

运行结果:

true

总结

JS中字符串包含是一个常见的操作,通过ES6新增的方法以及传统的indexOf()lastIndexOf()方法,我们可以方便地判断一个字符串是否包含另一个字符串。另外,正则表达式也提供了一种更灵活的方式进行字符串包含判断。在实际开发中,根据需求选择合适的方法来判断字符串包含关系,将会提高代码的效率和可读性。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程