JavaScript String Search Methods: A Comprehensive Tutorial

avaScript provides several built-in methods to search strings, allowing you to locate substrings, check for their existence, and extract information from them.

This tutorial will explore the commonly used string search methods in JavaScript, demonstrating each with practical code examples.

1. indexOf()

The indexOf() method returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1. You can also provide a second optional parameter to specify the position to start the search.

Example 1: Using indexOf()

const text = 'Hello, JavaScript! JavaScript is great!';

console.log(text.indexOf('JavaScript')); // Output: 7
console.log(text.indexOf('JavaScript', 8)); // Output: 20 (starts searching from index 8)
console.log(text.indexOf('Python')); // Output: -1 (not found)

Explanation: indexOf() returns the index of the first occurrence of the specified substring. If the substring is not found, it returns -1.

2. lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified value in a string. It searches the string backward from the end to the beginning. You can provide a second optional parameter to specify the starting position for the search.

Example 2: Using lastIndexOf()

const text = 'JavaScript is great. I love JavaScript!';

console.log(text.lastIndexOf('JavaScript')); // Output: 27
console.log(text.lastIndexOf('JavaScript', 25)); // Output: 0 (starts searching backward from index 25)
console.log(text.lastIndexOf('Python')); // Output: -1 (not found)

Explanation: lastIndexOf() returns the index of the last occurrence of the specified substring. If the substring is not found, it returns -1.

3. includes()

The includes() method checks if a string contains a specified value. It returns true if the value is found; otherwise, it returns false. You can also provide a second optional parameter to specify the position to start the search.

Example 3: Using includes()

const text = 'JavaScript is versatile.';

console.log(text.includes('JavaScript')); // Output: true
console.log(text.includes('Python')); // Output: false
console.log(text.includes('versatile', 15)); // Output: true (starts searching from index 15)

Explanation: includes() performs a case-sensitive search and returns a boolean indicating whether the specified value exists in the string.

4. startsWith()

The startsWith() method checks if a string starts with a specified value. It returns true if the string starts with the value; otherwise, it returns false. You can provide an optional second parameter to specify the starting position for the check.

Example 4: Using startsWith()

const text = 'JavaScript is powerful.';

console.log(text.startsWith('JavaScript')); // Output: true
console.log(text.startsWith('powerful')); // Output: false
console.log(text.startsWith('is', 11)); // Output: true (checks starting from index 11)

Explanation: startsWith() checks if the string begins with the specified substring, considering an optional starting position.

5. endsWith()

The endsWith() method checks if a string ends with a specified value. It returns true if the string ends with the value; otherwise, it returns false. You can provide an optional second parameter to specify the length of the string to consider for the check.

Example 5: Using endsWith()

const text = 'JavaScript is powerful.';

console.log(text.endsWith('powerful.')); // Output: true
console.log(text.endsWith('JavaScript')); // Output: false
console.log(text.endsWith('JavaScript', 10)); // Output: true (considers only the first 10 characters)

Explanation: endsWith() checks if the string ends with the specified substring, considering an optional length of the string.

6. search()

The search() method searches a string for a match against a regular expression and returns the index of the first match. If no match is found, it returns -1.

Example 6: Using search()

const text = 'JavaScript is versatile and powerful.';

console.log(text.search(/versatile/)); // Output: 13
console.log(text.search(/Python/)); // Output: -1 (not found)
console.log(text.search(/power/i)); // Output: 28 (case-insensitive search using the 'i' flag)

Explanation: The search() method takes a regular expression and returns the index of the first match. It is more flexible than indexOf() as it allows regular expressions for more complex searching.

7. match()

The match() method retrieves the result of matching a string against a regular expression. It returns an array of matched results or null if no match is found.

Example 7: Using match()

const text = 'JavaScript, Python, Ruby, JavaScript';

console.log(text.match(/JavaScript/)); // Output: ['JavaScript'] (first match only)
console.log(text.match(/JavaScript/g)); // Output: ['JavaScript', 'JavaScript'] (all matches using 'g' flag)
console.log(text.match(/python/i)); // Output: ['Python'] (case-insensitive search using 'i' flag)

Explanation: The match() method can return multiple matches when used with the global (g) flag. It also supports case-insensitive searches using the i flag.

8. matchAll()

The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups. It must be used with the g flag in the regular expression.

Example 8: Using matchAll()

const text = 'The prices are $5, $10, and $15.';
const regex = /\$(\d+)/g;

const matches = text.matchAll(regex);

for (const match of matches) {
  console.log(match[0]); // Output: $5, $10, $15
  console.log(match[1]); // Output: 5, 10, 15 (capturing group)
}

Explanation: matchAll() returns an iterator that provides detailed information about each match, including capturing groups.

9. replace()

The replace() method searches a string for a specified value or a regular expression and returns a new string with the specified value(s) replaced.

Example 9: Using replace()

const text = 'JavaScript is great. I love JavaScript.';

console.log(text.replace('JavaScript', 'Python')); // Output: Python is great. I love JavaScript.
console.log(text.replace(/JavaScript/g, 'Python')); // Output: Python is great. I love Python.

Explanation: replace() replaces only the first occurrence by default. To replace all occurrences, use a regular expression with the global (g) flag.

10. replaceAll()

The replaceAll() method replaces all occurrences of a specified value in a string.

Example 10: Using replaceAll()

const text = 'JavaScript is great. JavaScript is fun.';

console.log(text.replaceAll('JavaScript', 'Python')); // Output: Python is great. Python is fun.

Explanation: Unlike replace(), replaceAll() is straightforward for replacing all instances of a substring without requiring a regular expression.

Conclusion

JavaScript provides a rich set of string search methods that allow you to find, check for, and extract parts of strings using simple or complex patterns.

From basic substring checks (includes(), indexOf(), startsWith(), endsWith()) to more powerful regular expression-based searches (search(), match(), matchAll()), these methods provide flexibility and control when working with textual data.

Experiment with these examples to get a better understanding of how to use string search methods effectively in your JavaScript projects!

Related posts

JavaScript Operator Precedence

JavaScript Reserved Keywords

JavaScript Syntax Tutorial with Examples