avaScript has a bunch of built-in functions for finding bits of text inside other text. If you gotta check input look for specific words, or tweak text, these functions are pretty handy.
We’re gonna dive into the different ways you can hunt for strings in JavaScript with some easy-to-follow code snippets.
1. indexOf()
Shows you where a certain piece of text shows up first. If it’s not there, you get a -1
.
Example:
<script> let text = "Learn JavaScript programming"; let position = text.indexOf("JavaScript"); console.log(position); // Output: 6 </script>
2. lastIndexOf()
Finds the position where a certain word or phrase shows up for the final time.
Example:
<script> let story = "One fish, two fish red fish blue fish"; let endSpot = story.lastIndexOf("fish"); console.log(endSpot); ' // Output: 36 </script>
3. includes()
Confirms the presence of specific text within a string by giving a ‘yes’ or ‘no’ answer.
Example:
<script> let text = "JavaScript is fun"; let wordFound = text.includes("fun");' console.log(wordFound); // Output: true </script>
4. search()
Lookin’ for a hit with a regular expression? This will tell ya where it’s at, or give ya a -1
if it’s nowhere.
Peek at this:
<script> "A bunch of text is "Contact: [email protected]"; You're looking and boom there it is at "info"; If you're curious where just eyeball the console; Speaks for itself, right? // It pops: 9 </script>
5. match()
You got a string and need a regular expression showdown? This baby’s gonna dig up the details for ya.
<script>
Here's the lowdown: "ID1234 found at 3PM";
You toss that into the ring with a regex;
Eager to see what you got? Check the console;
And there it is, plain as day: ID1234 // You got it: ID1234
</script>
6. matchAll()
Provides every match from a regular expression via an iterable collection. The global (g
) marker is a must-have.
Example:
<script> let text = "cat, bat hat"; let pattern = /\w+at/g; let allMatches = text.matchAll(pattern); for (let oneMatch of allMatches) { console.log(oneMatch[0]); } // The result you see: // cat // bat // hat </script>
Here’s how you do it:
Wrap Up
When you need to deal with text in code, JavaScript comes with a bunch of helpful methods for searching strings. You might search for a specific word, figure out where in a string something is, or get fancy with patterns using regex tools. For sure, these are key if you wanna handle string data like a pro.