When working with text in JavaScript, a very common task is searching for words, characters, or patterns inside a string. For example:
-
Checking if an email contains
@ -
Finding a word inside a paragraph
-
Validating usernames
-
Filtering search results
JavaScript provides several powerful methods for string searching.
What is String Search in JavaScript?
String search means finding:
-
A character inside a string
-
A word inside a sentence
-
The position (index) of text
-
Whether text exists or not
JavaScript offers built-in methods such as:
-
indexOf() -
lastIndexOf() -
includes() -
startsWith() -
endsWith() -
search()
These methods help you work with text efficiently.
1. indexOf() – Find the Position of Text
The indexOf() method returns the position of the first match.
Output:
7
Explanation:
-
Counting starts from index
0 -
If the text is not found, it returns
-1
2. lastIndexOf() – Find the Last Occurrence
If a word appears multiple times, lastIndexOf() gives the last position.
This is useful when analyzing long text.
3. includes() – Check if Text Exists (Most Beginner-Friendly)
The includes() method returns true or false.
Why beginners love includes():
-
Easy to read
-
Returns direct boolean
-
Great for validation logic
4. startsWith() – Check Beginning of String
Useful for:
-
File validation
-
URL checks
-
Command prefixes
5. endsWith() – Check End of String
Useful for:
-
File type validation
-
Extension checks
6. search() – Search Using Pattern
The search() method works like indexOf() but also supports regular expressions.
Returns the starting position of the match.
Common Mistakes Beginners Make
Forgetting that indexOf() returns -1
Correct Way
Or better:
Why String Search is Important in JavaScript
Mastering JavaScript string search methods helps you:
-
Validate user input
-
Build search features
-
Filter data
-
Handle forms correctly
-
Improve interview performance
-
Build real-world applications
Almost every web app uses string searching.
String search in JavaScript is a fundamental skill every developer must learn. Methods like includes(), indexOf(), and startsWith() make it easy to find and validate text efficiently.