HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript String Search

String Search Methods

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

String indexOf(

Searches for a specified substring within a string and returns the index of the first occurrence.

Returns -1 if the substring is not found.

Example

const str = "Hello World";
console.log(str.indexOf("World")); // Output: 6
console.log(str.indexOf("Universe")); // Output: -1

String lastIndexOf()

Searches for a specified substring within a string and returns the index of the last occurrence.

Returns -1 if the substring is not found..

Example

const str = "Hello World";
console.log(str.lastIndexOf("o")); // Output: 7

String search()

Searches for a specified substring or regular expression within a string and returns the index of the first occurrence.

Returns -1 if the substring or regular expression is not found.

Example

const str = "Hello World";
console.log(str.search("World")); // Output: 6
console.log(str.search(/world/i)); // Output: -1 (case-insensitive search)

String match()

Searches a string for a specified pattern using a regular expression and returns an array of matches.

Returns null if no matches are found.

Example

const str = "Hello World";
console.log(str.match(/o/g)); // Output: ["o", "o"]

String includes()

Determines whether a string contains a specified substring.

Returns true if the substring is found, otherwise false.

Example

const str = "Hello World";
console.log(str.includes("World")); // Output: true
console.log(str.includes("Universe")); // Output: false

startsWith() and endsWith():

Checks if a string starts or ends with a specified substring.

Returns true if the string starts or ends with the substring, otherwise false..

Example

const str = "Hello World";
console.log(str.startsWith("Hello")); // Output: true
console.log(str.endsWith("World")); // Output: true