JS String Search 🎯

beginner
22 min

JS String Search 🎯

Welcome to our deep dive into JavaScript (JS) String Search! In this comprehensive guide, we'll explore how to search for strings in JavaScript, covering both basic and advanced concepts. By the end of this tutorial, you'll have a solid understanding of string search methods, ready to apply them in your own projects.

Let's start by understanding what a string is and why we need to search within them.

What is a String in JavaScript? 📝

A string in JavaScript is a series of characters enclosed in single quotes (') or double quotes ("). For example:

javascript
let myString = "Hello, World!";

Strings are crucial in programming because they allow us to work with text, which is an essential part of any application or website.

Why Search for Strings? 💡

Searching for strings is a common operation in programming. It helps us find specific pieces of text within larger strings, making it easier to work with and process data effectively.

String Search Methods in JavaScript 🎯

JavaScript provides several built-in methods to search for strings. In this tutorial, we'll focus on two primary methods: indexOf() and includes().

indexOf() 📝

The indexOf() method returns the position (index) at which a specified string begins within the calling string. If the specified string is not found, it returns -1.

javascript
let myString = "Hello, World!"; console.log(myString.indexOf("World")); // Output: 7

Pro Tip:

The indexOf() method is case-sensitive. If you want to perform a case-insensitive search, you can convert both the search string and the target string to uppercase or lowercase before comparing.

includes() 📝

The includes() method determines whether a specified string is present within the calling string. It returns true if it is found, and false otherwise.

javascript
let myString = "Hello, World!"; console.log(myString.includes("World")); // Output: true

Pro Tip:

The includes() method is case-insensitive by default.

Practical Examples 🎯

Now, let's put these methods into action with some practical examples.

Example 1: Searching for a Specific Word

javascript
let myString = "I am learning JavaScript at CodeYourCraft."; console.log(myString.indexOf("JavaScript")); // Output: 22 console.log(myString.includes("CodeYourCraft")); // Output: true

Example 2: Searching for Multiple Words and Case-Insensitive Search

javascript
let myString = "I am Learning jAvAsCrIpT At CoDeYoUrCrAft."; let searchWord = "javascript"; console.log(myString.indexOf(searchWord) !== -1); // Output: true

Quiz 🎯

Quick Quiz
Question 1 of 1

Which method returns the position at which a specified string begins within the calling string?

Quick Quiz
Question 1 of 1

Is the `includes()` method case-sensitive?