1. Answers
  2. Check if a String Contains a Phrase in TypeScript

How do I check if a string contains a phrase in TypeScript?

To check if a string contains a specific phrase in TypeScript, you can use the includes method available on string objects. This method returns true if the string contains the specified substring, and false otherwise.

Here is a TypeScript program that demonstrates how to do this:

// Define the main string and the phrase to check
const mainString: string = "The quick brown fox jumps over the lazy dog";
const phrase: string = "brown fox";

// Use the includes method to check if the phrase is in the main string
const containsPhrase: boolean = mainString.includes(phrase);

// Output the result
console.log(`Does the main string contain the phrase? ${containsPhrase}`);

In this program:

  1. We define a mainString that contains the text we want to search within.
  2. We define a phrase that we want to check for within the mainString.
  3. We use the includes method on mainString with phrase as an argument. This method checks if phrase is a substring of mainString and returns a boolean value.
  4. We log the result to the console to see if the main string contains the phrase.

This method is simple and effective for checking the presence of a substring within a string in TypeScript.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up