JS String Search

JavaScript String Search Methods

A string is a sequence of characters used to represent text or data. Strings can be enclosed within single or double quotes. Here we are using some common approaches to search for a particular string/character in a given string.

String Search Methods

Below are the approaches to search strings in JavaScript:


Using the search() Method

The search() method searches for a substring in a string and returns the index of the first occurrence, or -1 if not found.

search() Example

// Define a string variable
let str1 = "Intricate Devo, A coding learning platform";

// Use the search() method to search for "coding" let result = str1.search("coding"); console.log(result); // Output: 17


Using the match() Method

The match() method is an inbuilt function in JavaScript used to search a string for a match against any regular expression. It returns an array of matches.

match() Example

// Define a string variable
let str1 = "Intricate Devo, A coding learning platform";

// Use the match() method to search for "coding" let result = str1.match(/coding/g); console.log(result); // Output: [ 'computer' ]


Using the includes() Method

The includes() method checks if a string contains a specific substring, returning true if found, false if not.

includes() Example

// Define a string variable
let str1 = "Intricate Devo, A coding learning platform";

// Use the includes() method to check for "learning" let result = str1.includes("learning"); console.log(result); // Output: true


Using startsWith() Method

The startsWith() method checks if a string starts with a specified substring, returning true if it matches, false otherwise.

startsWith() Example

// Define a string variable
let str1 = "Intricate Devo, A coding learning platform";

// Use the startsWith() method to check the beginning let result = str1.startsWith("Intricate Devo"); console.log(result); // Output: true


Using endsWith() Method

The endsWith() method checks if a string ends with a specified substring, returning true if it matches, false otherwise.

endsWith() Example

// Define a string variable
let str1 = "Intricate Devo, A coding learning platform";

// Use the endsWith() method to check the ending let result = str1.endsWith("platform"); console.log(result); // Output: true


Using lastIndexOf() Method

The lastIndexOf() method searches for the last occurrence of a substring in a string and returns its index or -1 if not found.

lastIndexOf() Example

// Define a string variable
let str1 = "Intricate Devo, A coding learning platform";

// Use the lastIndexOf() method to find last occurrence let result = str1.lastIndexOf("Intricate"); console.log(result); // Output: 15

Question 1 ?

Which method returns the index of the first occurrence of a substring?