TypeScript String search()

In this chapter, we will explore the search() method in TypeScript. This method is a built-in function that helps in searching a string for a match against a regular expression and returns the index of the first match. Understanding how to use search() is useful for locating patterns within strings.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The search() method executes a search for a match between a regular expression and a string. It returns the index of the first match or -1 if no match is found.

2. Syntax

string.search(regexp);

Parameters

  • regexp: A regular expression object containing the pattern to search for. If a non-RegExp object is passed, it is implicitly converted to a RegExp with the global search.

Return Value

The method returns a number representing the index of the first match of the regular expression within the string. If no match is found, it returns -1.

3. Examples

Let's look at some examples to understand how search() works in TypeScript.

Example 1: Basic Usage

In this example, we use search() to find the index of the first occurrence of a pattern in a string.

let str: string = "Hello, TypeScript!";
let result = str.search(/TypeScript/);
console.log(result); // Output: 7

Example 2: No Match Found

In this example, we use search() with a pattern that does not exist in the string.

let str: string = "Hello, TypeScript!";
let result = str.search(/JavaScript/);
console.log(result); // Output: -1

Example 3: Case-Insensitive Search

In this example, we use search() with a case-insensitive regular expression to find a match regardless of its case.

let str: string = "Hello, TypeScript!";
let result = str.search(/typescript/i);
console.log(result); // Output: 7

Example 4: Using Special Characters

In this example, we use search() with a regular expression containing special characters.

let str: string = "The price is $100.";
let result = str.search(/\$\d+/);
console.log(result); // Output: 13

Example 5: Searching for a Digit

In this example, we use search() to find the index of the first digit in a string.

let str: string = "The year is 2024.";
let result = str.search(/\d/);
console.log(result); // Output: 12

4. Conclusion

In this chapter, we explored the search() method in TypeScript, which is used to search a string for a match against a regular expression and return the index of the first match. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use search() effectively can help in various string manipulation tasks in TypeScript, especially when locating patterns within strings.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare