📜  JavaScript String include()(1)

📅  最后修改于: 2023-12-03 14:42:27.106000             🧑  作者: Mango

JavaScript String includes()

The includes() method is used to check if one string contains another string. It returns true if the specified string is found, otherwise it returns false. This method is case-sensitive.

Syntax
string.includes(searchString[, position])
Parameters
  • searchString: The string to search for within the calling string.
  • position (optional): The position at which to start searching within the calling string. Defaults to 0.
Return Value
  • Returns true if the calling string contains the searchString, otherwise returns false.
Examples
const str = 'Hello, JavaScript';

console.log(str.includes('Hello')); // true
console.log(str.includes('world')); // false
console.log(str.includes('JavaScript')); // true

// Using position parameter
console.log(str.includes('Hello', 1)); // false
console.log(str.includes('ello', 1)); // true

In the above example, we have a string str that contains the phrase "Hello, JavaScript". We use the includes() method to check if str includes certain strings. The method returns true if the search string is found, and false otherwise. By providing a position parameter, you can specify a starting index for the search.

Case Sensitivity
const str = 'Hello, JavaScript';

console.log(str.includes('hello')); // false
console.log(str.includes('JavaScript')); // true

The includes() method is case-sensitive, so if the search string has a different case than the calling string, it will return false.

Compatibility

The includes() method is available in all modern browsers and is supported in ECMAScript 6 (ES6) and later versions.

For older browser support or versions before ES6, you can use other methods like indexOf() or search() to achieve similar functionality.

Conclusion

The includes() method is a useful tool for checking whether a string contains a specific substring or not. It simplifies the process of substring search and eliminates the need for additional conditional statements.