search in javascript

To search for a specific element or substring in a string or an array in JavaScript, there are several methods available.

  1. indexOf() method: The indexOf() method returns the index of the first occurrence of the specified element or substring in the string or array. If it doesn't find the element, it returns -1.
index.tsx
const str = 'JavaScript is awesome';
const index = str.indexOf('awesome');
console.log(index); // Output: 13
109 chars
4 lines
  1. includes() method: The includes() method checks whether the string or array contains the specified element or substring. It returns a Boolean value.
index.tsx
const str = 'JavaScript is awesome';
const isPresent = str.includes('awesome');
console.log(isPresent); // Output: true
120 chars
4 lines
  1. Regular expressions: Regular expressions in JavaScript are powerful tools that can be used to search for patterns in strings. The search() method returns the index of the first match, and the match() method returns an array of matches.
index.tsx
const str = 'JavaScript is awesome';
const regex = /awesome/i;
const index = str.search(regex);
console.log(index); // Output: 13

const matches = str.match(regex);
console.log(matches); // Output: ["awesome"]
210 chars
8 lines
  1. find() method: The find() method is used to search through an array and return the first element that matches the provided condition.
index.tsx
const arr = [5, 10, 15, 20];
const result = arr.find(item => item > 12);
console.log(result); // Output: 15
108 chars
4 lines
  1. filter() method: The filter() method is used to search through an array and return all elements that match the provided condition.
index.tsx
const arr = [5, 10, 15, 20];
const result = arr.filter(item => item > 12);
console.log(result); // Output: [15, 20]
116 chars
4 lines

gistlibby LogSnag