JavaScript String Search Methods
Searching for substrings within strings is a common task in JavaScript. The language provides several methods to locate and extract parts of a string based on search criteria. This article covers the primary string search methods available in JavaScript, including indexOf()
, lastIndexOf()
, includes()
, startsWith()
, and endsWith()
.
1. indexOf()
The indexOf()
method returns the index of the first occurrence of a specified substring. If the substring is not found, it returns -1
.
// Example
const str = 'Hello, world!';
console.log(str.indexOf('world')); // Output: 7
console.log(str.indexOf('foo')); // Output: -1
2. lastIndexOf()
The lastIndexOf()
method returns the index of the last occurrence of a specified substring. If the substring is not found, it returns -1
.
// Example
const str = 'Hello, world! World is big!';
console.log(str.lastIndexOf('world')); // Output: 7 (case-sensitive)
console.log(str.lastIndexOf('World')); // Output: 20
console.log(str.lastIndexOf('foo')); // Output: -1
3. includes()
The includes()
method checks if a string contains a specified substring. It returns true
if the substring is found and false
otherwise. It is case-sensitive.
// Example
const str = 'Hello, world!';
console.log(str.includes('world')); // Output: true
console.log(str.includes('foo')); // Output: false
4. startsWith()
The startsWith()
method checks if a string starts with a specified substring. It returns true
if it does and false
otherwise. It is case-sensitive.
// Example
const str = 'Hello, world!';
console.log(str.startsWith('Hello')); // Output: true
console.log(str.startsWith('world')); // Output: false
5. endsWith()
The endsWith()
method checks if a string ends with a specified substring. It returns true
if it does and false
otherwise. It is case-sensitive.
// Example
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // Output: true
console.log(str.endsWith('Hello')); // Output: false
Conclusion
JavaScript offers several methods for searching within strings. The indexOf()
and lastIndexOf()
methods provide positions of substrings, while includes()
, startsWith()
, and endsWith()
are useful for checking the presence and position of substrings in a more straightforward manner. Mastering these methods will help you efficiently handle and manipulate string data in your JavaScript projects.
Comments
Post a Comment