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.
Below are the approaches to search strings in JavaScript:
search() - Searches for a substring and returns the index of first matchmatch() - Searches using regular expressions and returns matches in arrayincludes() - Checks if string contains a specific substringstartsWith() - Checks if string starts with a specified substringendsWith() - Checks if string ends with a specified substringlastIndexOf() - Searches for last occurrence and returns its indexThe search() method searches for a substring in a string and returns the index of the first occurrence, or -1 if not found.
// 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
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.
// 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' ]
The includes() method checks if a string contains a specific substring, returning true if found, false if not.
// 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
The startsWith() method checks if a string starts with a specified substring, returning true if it matches, false otherwise.
// 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
The endsWith() method checks if a string ends with a specified substring, returning true if it matches, false otherwise.
// 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
The lastIndexOf() method searches for the last occurrence of a substring in a string and returns its index or -1 if not found.
// 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
Which method returns the index of the first occurrence of a substring?