String Search in JavaScript

JavaScript Guide

Becoming Sherlock Holmes Inside Text 🕵️‍♂️🔎

Imagine a user…
They type something into an input field.
And in the background, JavaScript says:

“Is this word here?
If yes, where exactly?
How many times does it appear?
Or is it just made up?” 😏

That’s exactly what String Search is:
JavaScript’s detective skill.
It dives into the text, follows clues, gathers evidence, and gives you clear answers.


1. What Is String Search? (Short Definition + Real-Life Logic)

String search means searching, finding, locating, or analyzing one piece of text inside another string.

📌 Where do we use it in real life?

  • 🔍 Search boxes (Google, site search)
  • 💬 Chat message filtering
  • 🚫 Profanity / spam prevention
  • ✅ Form validation
  • 🎮 Game commands (/help, /quit)
  • 🧾 Log & text analysis

So honestly…
Saying “I do frontend” without knowing string search
is a bit ambitious 😄


2. includes() – “Is This Text Here?” ✅❌

Beginner-level, but ridiculously powerful.

let text = "Learning JavaScript is very enjoyable";

console.log(text.includes("JavaScript")); // true
console.log(text.includes("Python"));     // false

What Does This Code Do?

  • Checks whether the given word
  • Exists inside the text string
  • Returns only true or false

🧠 In short, includes() asks:

“Is it there or not? I don’t care about details.”


🎯 Real-Life Usage

let userMessage = "I am learning JavaScript";

if (userMessage.includes("JavaScript")) {
  console.log("You are in the right place 😎");
}

📌 If the user mentions JavaScript, we respond accordingly.
That’s basically how chatbots think.


⚠️ Uppercase – Lowercase Trap

"JavaScript".includes("javascript"); // false 😱

Because JavaScript is case-sensitive.

✅ Solution (golden rule):

text.toLowerCase().includes("javascript");

💡 Tip:
Always use toLowerCase() with user input.


3. indexOf() – “Where Does It Appear?” 📍

Now we go full detective mode.

let sentence = "Learning JavaScript is very enjoyable";

console.log(sentence.indexOf("Learning")); // 0
console.log(sentence.indexOf("Python"));   // -1

What Does This Mean?

  • If found → returns the starting index
  • If not found → returns -1

📌 -1 means:

“I searched everywhere. It’s not here.”


🧠 Why Is This Important?

if (sentence.indexOf("JS") !== -1) {
  console.log("JS found 🎯");
}

This pattern appears very often in:

  • Old projects
  • Legacy codebases
  • Performance-focused code

🧩 Tip: includes() or indexOf()?

SituationUse
Just check existenceincludes()
Find the positionindexOf()
Old browser supportindexOf()

4. lastIndexOf() – “Where Was It Last Seen?” ⏪

What if a word appears multiple times?

let text = "JS learn, JS write, JS love";

console.log(text.indexOf("JS"));      // 0
console.log(text.lastIndexOf("JS"));  // 17

Logic:

  • indexOf() → first occurrence
  • lastIndexOf()last occurrence

📌 Perfect for:

  • Log analysis
  • Message history
  • Repeated keywords

5. startsWith() – “Does It Start With This?” 🚪

let command = "/help";

console.log(command.startsWith("/")); // true

What Is It Used For?

  • Is it a command?
  • Is the URL valid?
  • Does the filename follow the rules?

🎯 Example:

let url = "https://google.com";

if (url.startsWith("https")) {
  console.log("Secure connection 🔒");
}


6. endsWith() – “Does It End With This?” 🏁

let fileName = "photo.png";

console.log(fileName.endsWith(".png")); // true

🎯 Real-world usage:

if (fileName.endsWith(".jpg") || fileName.endsWith(".png")) {
  console.log("This is an image file 🖼️");
}

This is the heart of file upload validation ❤️


7. search() – The Gateway to the Regex World 🎭

let text = "JavaScript is still popular in 2026";

console.log(text.search("2026")); // 29

But the real power comes with Regex:

console.log(text.search(/\d+/)); // finds a number

Logic:

  • Searches using a pattern
  • Found → returns index
  • Not found → returns -1

📌 search() = Regex + index


8. match() – “Bring Me Everything” 📦

let text = "JS, JS and more JS";

console.log(text.match(/JS/g));
// ["JS", "JS", "JS"]

What Does It Do?

  • Returns all matches as an array

🎯 Count occurrences:

let count = text.match(/JS/g).length;
console.log(count); // 3

🧠 A golden method for:

  • Spam detection
  • Profanity filters
  • Keyword analysis

9. Mini Project: Search Box Logic 🧪

function searchText(text, keyword) {
  if (text.toLowerCase().includes(keyword.toLowerCase())) {
    return "Found 🎯";
  }
  return "Not found ❌";
}

console.log(searchText("I am learning JavaScript", "script"));

What Happened Here?

  1. We received two strings from the user
  2. Converted both to lowercase
  3. Performed the search
  4. Returned the result

👉 This is 70% of a real search bar logic.


10. Unusual but Extremely Useful Tips 💎

🔹 How many words?

let sentence = "JavaScript is really really great";
console.log(sentence.split(" ").length);

🔹 Emojis can be searched too 😄

"Hello 😊".includes("😊"); // true

🔹 Censor a word

let text = "This is a very bad thing";
console.log(text.replace("bad", "***"));


Conclusion: String Search = JavaScript’s Hidden Superpower 🦸‍♂️

Someone who knows string search:

  • Builds better UIs
  • Creates smarter applications
  • Stands out in interviews
  • Writes more professional code

📌 Easy-to-remember summary:

  • includes() → is it there?
  • indexOf() → where is it?
  • lastIndexOf() → where was it last?
  • startsWith() → does it start with this?
  • endsWith() → does it end with this?
  • match() → give me all matches

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir