JavaScript String Search Methods

JavaScript provides several methods for searching within strings. Here are some important methods:

1. indexOf()

Returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1.


const str = 'JavaScript is fun';
console.log(str.indexOf('fun')); // 15
console.log(str.indexOf('Python')); // -1

            

2. lastIndexOf()

Returns the index of the last occurrence of a specified value in a string. If the value is not found, it returns -1.


const str = 'JavaScript is fun and JavaScript is great';
console.log(str.lastIndexOf('JavaScript')); // 33
console.log(str.lastIndexOf('Python')); // -1

            

3. includes()

Determines whether a string contains the specified value and returns a boolean value.


const str = 'JavaScript is fun';
console.log(str.includes('fun')); // true
console.log(str.includes('Python')); // false

            

4. search()

Searches for a match between a regular expression and a string. Returns the index of the match or -1 if no match is found.


const str = 'JavaScript is powerful';
console.log(str.search(/powerful/)); // 16
console.log(str.search(/Python/)); // -1

            

5. match()

Searches for a match between a regular expression and a string. Returns an array of matches or null if no match is found.


const str = 'JavaScript, Python, Ruby';
console.log(str.match(/Python/)); // ['Python']
console.log(str.match(/Java/)); // ['Java']