JavaScript Tutorial

JavaScript String Search

JavaScript में String Searching के लिए कई methods होते हैं, जिनकी मदद से हम किसी word, letter या pattern को string के अंदर ढूँढ़ सकते हैं।
इस अध्याय में आप सीखेंगे:


🔹 1. indexOf()

यह method string के अंदर किसी substring की पहली बार मौजूदगी का index return करता है।
अगर substring नहीं मिलता तो -1 return होता है।

Syntax:

string.indexOf(searchValue, start)

Example:

let text = "JavaScript is awesome!";
let result = text.indexOf("is");
console.log(result);  // Output: 11

🔹 2. lastIndexOf()

यह method substring की आखिरी बार मौजूदगी का index return करता है।

Example:

let text = "Learn JS and love JS";
let result = text.lastIndexOf("JS");
console.log(result);  // Output: 17

❗ ये methods case-sensitive होते हैं।


🔹 3. search()

यह method string में substring या regular expression को ढूँढ़ता है और match का index return करता है।
यह भी match न मिलने पर -1 return करता है।

Example 1: Simple word search

let str = "Welcome to JavaScript!";
let result = str.search("JavaScript");
console.log(result);  // Output: 11

Example 2: Case-sensitive search

let str = "JavaScript is Powerful!";
console.log(str.search("script"));  // Output: -1

Example 3: With Regular Expression (case-insensitive)

let str = "JavaScript is Powerful!";
let result = str.search(/script/i);
console.log(result);  // Output: 4

🔹 4. includes()

यह method check करता है कि string में कोई substring मौजूद है या नहीं
Boolean value (true या false) return करता है।

Example:

let message = "Coding is fun!";
console.log(message.includes("fun"));      // Output: true
console.log(message.includes("Fun"));      // Output: false (case-sensitive)

🔹 5. Search with startsWith() and endsWith()

Example:

let msg = "Hello JavaScript";
console.log(msg.startsWith("Hello"));   // Output: true
console.log(msg.endsWith("Script"));    // Output: false

Compare Methods – Summary Table

Methodक्या करता है?Return
indexOf()First occurrence का indexindex / -1
lastIndexOf()Last occurrence का indexindex / -1
search()Regular expression या substring का indexindex / -1
includes()Substring मौजूद है या नहींtrue / false
startsWith()String की शुरुआत check करता हैtrue / false
endsWith()String के अंत की जाँच करता हैtrue / false

अभ्यास प्रश्न

  1. indexOf() और search() में क्या अंतर है?
  2. includes() method किस प्रकार का value return करता है?
  3. नीचे दिए गए code का output क्या होगा? let str = "JavaScript is simple"; console.log(str.search("simple")); console.log(str.includes("Java"));
  4. किसी string में “html” word की मौजूदगी check करने के लिए कौन-सा method सबसे अच्छा रहेगा? क्यों?
  5. एक ऐसा उदाहरण दीजिए जहाँ search() method में regular expression इस्तेमाल किया गया हो।