Remove the Last Character from a String in TypeScript

In this tutorial, I will explain how to remove the last character from a string in TypeScript using various methods. We will explore different approaches, including using the slice() method, the substring() method, and the replace() method.

Remove the Last Character from a String in TypeScript

I will now show you how to remove the last character from a string in TypeScript using the methods below.

1. Using the slice() Method

The slice() method extracts a portion of a string and returns it as a new string, without modifying the original one.

To remove the last character, you simply slice from the beginning (index 0) to the second-to-last character.

Syntax

string.slice(0, -1)

Example

let cityName: string = "San Francisco";
let modifiedCityName: string = cityName.slice(0, -1);
console.log(modifiedCityName); // Output: "San Francisc"

In this example, the slice() method is called on the cityName string with the arguments 0 and -1. This tells TypeScript to start at the beginning of the string (index 0) and go up to, but not including, the last character (index -1).

I executed the above code using VS code, and you can see the output in the screenshot below:

Remove the Last Character from a String in TypeScript

Check out TypeScript Enums vs String Literal Unions

2. Using the substring() Method

The substring() method is another useful method for extracting parts of a string in TypeScript. Unlike slice(), substring() does not accept negative indices. To remove the last character, you need to provide the starting index and the length of the new string.

Syntax

string.substring(0, string.length - 1)

Example:

Here is an example.

let stateName: string = "California";
let modifiedStateName: string = stateName.substring(0, stateName.length - 1);
console.log(modifiedStateName); // Output: "Californi"

In this example, substring(0, stateName.length - 1) extracts the string from the beginning (index 0) to the second-to-last character (stateName.length - 1).

Check out Create Multiline Strings in TypeScript

3. Using the replace() Method

The replace() method can also be used to remove the last character from a string. This method is typically used for replacing parts of a string with another string, but it can also be employed to remove characters by replacing them with an empty string.

Example:

let landmark: string = "Statue of Liberty!";
let modifiedLandmark: string = landmark.replace(/.$/, "");
console.log(modifiedLandmark); // Output: "Statue of Liberty"

In this example, the regular expression /. matches the last character of the string, and the replace() method replaces it with an empty string, effectively removing it.

You can see the exact output in the screenshot below:

TypeScript Remove the Last Character from a String

Check out Remove a Substring from a String in TypeScript

4. Using Array Conversion with split() and join()

You can treat a string like an array by splitting it into characters, removing the last one, and then joining it back together.

This method is more verbose but shows how strings can be manipulated as arrays. It’s useful when you want to do more complex operations, like replacing or filtering characters before joining.

Here is an example and the complete code.

let lastName: string = "Williams_";
let cleanedLastName: string = lastName.split('').slice(0, -1).join('');
console.log(cleanedLastName); // Output: Williams

5. Using Regular Expressions

You can remove the last character with a simple regex pattern for those comfortable with regular expressions.

Here is an example and the complete code.

let zipCode: string = "90210-";
let cleanedZip: string = zipCode.replace(/.$/, '');
console.log(cleanedZip); // Output: 90210

The regex /. $/ matches the last character of the string and replaces it with an empty string.

Check out Replace Characters in a String Using TypeScript

Handle Edge Cases While Removing the Last Character from a String

Make sure to check if the string is not empty before trying to remove the last character in TypeScript.

Empty Strings

Ensure your code can handle empty strings without throwing errors:

function safeTrim(str: string): string {
  return str.length > 0 ? str.slice(0, -1) : str;
}

console.log(safeTrim(""));        // Output: ""
console.log(safeTrim("John"));    // Output: "Joh"

Strings with One Character

Verify that your code works correctly with single-character strings:

let singleChar: string = "A";
let modifiedSingleChar: string = singleChar.slice(0, -1);
console.log(modifiedSingleChar); // Output: ""

Performance Considerations

When choosing a method to remove the last character from a string, consider the performance implications, especially if you work with large strings or perform the operation frequently.

Performance Comparison

While the performance difference between slice(), substring(), and replace() is generally negligible for small strings, slice() and substring() are often faster than replace() due to the overhead of regular expressions.

Example Performance Test

You can use the following code snippet to compare the performance of different methods:

console.time("slice");
for (let i = 0; i < 1000000; i++) {
  let result = "Washington".slice(0, -1);
}
console.timeEnd("slice");

console.time("substring");
for (let i = 0; i < 1000000; i++) {
  let result = "Washington".substring(0, "Washington".length - 1);
}
console.timeEnd("substring");

console.time("replace");
for (let i = 0; i < 1000000; i++) {
  let result = "Washington".replace(/.$/, "");
}
console.timeEnd("replace");

Conclusion

In this tutorial, I have explained how to remove the last character from a string in TypeScript using several methods, including slice(), substring(), and replace(). For most of the cases, I recommend using the slice(0, -1) for most of the cases.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.