Loading episodes…
0:00 0:00

Angular Find Substring in String

00:00
BACK TO HOME

Angular Find Substring in String

10xTeam December 03, 2023 2 min read

There are a few ways to find a substring in a string in Angular. Here are two of the most common methods:

Using the indexOf() method

The indexOf() method returns the index of the first occurrence of a substring in a string. If the substring is not found, it returns -1.

const str = 'This is a string';
const substring = 'is';
const index = str.indexOf(substring);
console.log(index); // Output: 2

Using the includes() method

The includes() method returns true if a substring is found in a string, and false if it is not.

const str = 'This is a string';
const substring = 'is';
const hasSubstring = str.includes(substring);
console.log(hasSubstring); // Output: true

Here is an example of how to use the indexOf() method to find all occurrences of a substring in a string:

const str = 'This is a string with is in it twice';
const substring = 'is';
let index = str.indexOf(substring);
while (index !== -1) {
  console.log(index);
  index = str.indexOf(substring, index + 1);
}

This code will print the following output:

2
5

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?