1. Answers
  2. How to check if 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, which is a part of the String prototype. This method determines whether one string may be found within another string, returning true or false as appropriate.

Here is a simple example of how you can use the includes method in TypeScript:

// Define a string
const mainString = "Hello, welcome to the world of TypeScript!";

// Define a phrase to search for
const phrase = "welcome";

// Check if the main string contains the phrase
const containsPhrase = mainString.includes(phrase);

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

Explanation:

  1. Define a string: We start by defining the main string in which we want to search for a phrase.
  2. Define a phrase: We then define the phrase we are looking to find within the main string.
  3. Check if the main string contains the phrase: We use the includes method on the main string, passing the phrase as an argument. This method returns true if the phrase is found within the main string, and false otherwise.
  4. Output the result: Finally, we output the result to the console.

Full Program

Here is the complete TypeScript program with comments:

// Define the main string
const mainString = "Hello, welcome to the world of TypeScript!";

// Define the phrase to search for
const phrase = "welcome";

// Use the includes method to check if the main string contains the phrase
const containsPhrase = mainString.includes(phrase);

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

This program will output true because the phrase “welcome” is indeed found within the main string “Hello, welcome to the world of TypeScript!”. If you change the phrase to something not present in the main string, the output will be false.

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