How do I check if a TypeScript string contains a certain piece of text?
I’m trying to check if a string imported into my application contains a specific substring in TypeScript. How can I achieve this?
How do I check if a TypeScript string contains a certain piece of text?
I’m trying to check if a string imported into my application contains a specific substring in TypeScript. How can I achieve this?
Using includes()
The simplest and most direct way is to use the includes()
method. It checks if a substring exists within a string in TypeScript, returning a boolean value. Here’s an example:
const text: string = "Hello, world!";
const containsText = text.includes("world"); // true
This approach is clean, readable, and works perfectly for straightforward substring checks.
Another option is the indexOf()
method, which provides the position of the first occurrence of the substring or -1
if it’s not found.
const text: string = "Hello, world!";
const containsText = text.indexOf("world") !== -1; // true
While it works similarly to includes()
, this method can also tell you where the substring starts, giving you more flexibility if you need its position. For example, you could even extract text from that position onward.
If you need more advanced matching capabilities, regular expressions (RegExp
) with the test()
method are a powerful choice.
const text: string = "Hello, world!";
const containsText = /world/.test(text); // true
This approach is especially useful when you need to match patterns instead of exact substrings. For instance, you could match case-insensitive text or specific word boundaries:
const containsText = /\bworld\b/i.test(text); // true
While it may be more complex than includes()
or indexOf()
, it’s a must-know for situations requiring pattern matching.