JavaScript String Search Methods
Last Updated :
17 Jun, 2024
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 from our given string.
Below are the approaches to search strings in JavaScript:
Using the search() Method
In this approach, we are using the search() method, this method searches for a substring in a string and returns the index of the first occurrence, or -1 if not found.
Syntax:
str1.search( A )
Example: In this example, we are using the search() method to search computer words from our given string.
JavaScript
let str1 = "GeeksforGeeks, A computer science portal";
let result = str1.search("computer");
console.log(result);
The match() method is an inbuilt function in JavaScript used to search a string for a match against any regular expression. it will return in array form.
Syntax:
str1.match( /word/g )
Example: In this example, we are using the match() method on a given string.
JavaScript
let str1 = "GeeksforGeeks, A computer science portal";
let result = str1.match(/computer/g);
console.log(result);
The includes() method checks if a string contains a specific substring, returning true if found, false if not.
Syntax:
str1.includes( "word" )
Example: In this example, we are using the includes() method to find the specific word from our given string.
JavaScript
let str1 = "GeeksforGeeks, A computer science portal";
let result = str1.includes("science");
console.log(result);
The startsWith() method checks if a string starts with a specified substring, returning true if it matches, false otherwise.
Syntax:
str1.startsWith( "word" )
Example: In this example, we are using the startsWith() method to find our specific word from our given string.
JavaScript
let str1 = "GeeksforGeeks, A computer science portal";
let result = str1.startsWith("GeeksforGeeks");
console.log(result);
The endsWith() method checks if a string ends with a specified substring, returning true if it matches, false otherwise.
Syntax:
str1.endsWith( "word" )
Example: In this example, we are using endsWith() to find the last word from our given string
JavaScript
let str1 = "GeeksforGeeks, A computer science portal";
let result = str1.endsWith("portal");
console.log(result);
The lastIndexOf() method searches for the last occurrence of a substring in a string and returns its index or -1 if not found.
Syntax:
str1.lastIndexOf( "word" )
Example: In this example, we are using the lastIndexOf() method to find the index of a given string.
JavaScript
let str1 = "GeeksforGeeks, A computer science portal";
let result = str1.lastIndexOf("A");
console.log(result);