Skip to main content

JavaScript String Search

By SamK
0
0 recommends
Topic(s)

JavaScript provides several methods to search for strings within another string.

String Search Methods

JavaScript provides several ways to search within a string.

  • String indexOf()
  • String lastIndexOf()
  • String search()
  • String match()
  • String matchAll()
  • String includes()
  • String startsWith()
  • String endsWith()

indexOf()

Returns the position of the first match, or -1 if not found.

let text = "Hello JavaScript!";
console.log(text.indexOf("JavaScript")); // Output: 6
console.log(text.indexOf("PHP"));     // Output: -1 (Not found)

lastIndexOf() 

Same as indexOf(), but searches from the end.

let text = "JavaScript is great, and JavaScript is powerful!";
console.log(text.lastIndexOf("JavaScript")); // Output: 25

search()

Returns the position of the first match but allows regex.

console.log(text.search(/JavaScript/)); // Output: 0
console.log(text.search(/PHP/i));    // Output: -1 (Case-insensitive search not found)

match() 

Returns an array of matches or null if no match is found.

console.log(text.match(/JavaScript/g)); 
// Output: ["JavaScript", "JavaScript"]

matchAll()

Provides match details including indexes.

let text = "JavaScript is great, and JavaScript is powerful!";
let matches = [...text.matchAll(/JavaScript/g)];

// Log results to console
console.log(matches); // Output: (2) [Array(1), Array(1)]

includes()

Returns true or false.

console.log(text.includes("great"));   // Output: true
console.log(text.includes("PHP"));  // Output: false

startsWith() & endsWith()

Checks if a string starts or ends with a specific value.

console.log(text.startsWith("JavaScript")); // Output: true
console.log(text.endsWith("powerful!"));   // Output: true

Questions & Answers