Mastering `endsWith` in TypeScript

In TypeScript, the endsWith method is a powerful string utility that allows developers to check whether a given string ends with a specified substring. This method can be extremely useful in various scenarios, such as data validation, text processing, and string manipulation. In this blog post, we will explore the fundamental concepts of the endsWith method in TypeScript, its usage, common practices, and best practices.

Table of Contents

  1. Fundamental Concepts of endsWith in TypeScript
  2. Usage Methods
  3. Common Practices
  4. Best Practices
  5. Conclusion
  6. References

Fundamental Concepts of endsWith in TypeScript

The endsWith method is a built - in method of the String object in JavaScript, and TypeScript, being a superset of JavaScript, inherits this functionality. The endsWith method takes two parameters:

  • searchString: This is the substring that you want to check if the string ends with.
  • length (optional): It is a number that represents the length of the string where the search should be performed. If this parameter is provided, the method will consider only the first length characters of the string.

The endsWith method returns a boolean value. It returns true if the string ends with the specified searchString, and false otherwise.

Usage Methods

Basic Usage

Here is a simple example of using the endsWith method:

let myString: string = "Hello, World!";
let result: boolean = myString.endsWith("World!");
console.log(result); // Output: true

Using the Optional length Parameter

let myString: string = "Hello, World!";
let result: boolean = myString.endsWith("Hello", 5);
console.log(result); // Output: true

In this example, we are specifying a length of 5. So, the endsWith method will only consider the first 5 characters of the string, and since the first 5 characters end with “Hello”, it returns true.

Common Practices

Data Validation

One common use case of the endsWith method is data validation. For example, you might want to ensure that a user - entered file name has a specific file extension.

function validateFileName(fileName: string): boolean {
    return fileName.endsWith('.jpg') || fileName.endsWith('.png');
}

let fileName: string = "image.jpg";
console.log(validateFileName(fileName)); // Output: true

Text Processing

In text processing, you can use the endsWith method to perform certain actions based on the ending of a string. For example, you might want to add a period to sentences that don’t end with one.

function addPeriodIfNeeded(sentence: string): string {
    if (!sentence.endsWith('.')) {
        return sentence + '.';
    }
    return sentence;
}

let sentence: string = "This is a sentence";
console.log(addPeriodIfNeeded(sentence)); // Output: This is a sentence.

Best Practices

Case Sensitivity

The endsWith method is case - sensitive. If you want to perform a case - insensitive check, you can convert both the string and the search string to either uppercase or lowercase before using the endsWith method.

let myString: string = "Hello, World!";
let searchString: string = "world!";
let result: boolean = myString.toLowerCase().endsWith(searchString.toLowerCase());
console.log(result); // Output: true

Error Handling

When using the length parameter, make sure it is a valid positive number. If the length parameter is negative or greater than the length of the string, it can lead to unexpected results. You can add some validation logic to handle such cases.

function safeEndsWith(str: string, searchStr: string, length?: number): boolean {
    if (length!== undefined && (length < 0 || length > str.length)) {
        return false;
    }
    return length? str.endsWith(searchStr, length) : str.endsWith(searchStr);
}

let myString: string = "Hello, World!";
let result: boolean = safeEndsWith(myString, "World!", 20);
console.log(result); // Output: false

Conclusion

The endsWith method in TypeScript is a simple yet powerful tool for string manipulation and validation. By understanding its fundamental concepts, usage methods, common practices, and best practices, you can effectively use this method in your TypeScript projects. Whether you are validating user input, processing text, or performing other string - related tasks, the endsWith method can help you write more robust and efficient code.

References