October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Remove a Character from a String in TypeScript

Use replace() for the first match, replaceAll() for every literal match, or slice() for removal at an index. Learn the key regex and Unicode caveats.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use replace() to remove the first matching string, replaceAll() to remove every literal match, or slice() to remove a code unit at a known index. Each method returns a new string; assign the result if you want to keep it.

Choose the removal method for your goal

Goal Use What it removes
Remove the first literal match text.replace(target, "") Only the first occurrence of the string target
Remove every literal match text.replaceAll(target, "") Every occurrence of the string target
Remove every match defined by a pattern text.replace(/[0-9]/g, "") All characters matched by the global regular expression
Remove at a known index text.slice(0, i) + text.slice(i + 1) One UTF-16 code unit starting at index i

These are standard JavaScript string methods available on TypeScript string values, not TypeScript-specific APIs. The TypeScript Handbook describes the string type and its JavaScript relationship at Basic Types.

As an Amazon Associate I earn from qualifying purchases.

Remove the first occurrence

Pass a string target to replace() when only the first occurrence should disappear:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const text: string = "a-b-c";
const result: string = text.replace("-", "");

console.log(result); // "ab-c"

A string pattern does not make replace() remove every match. For example, text.replace(".", "") removes the first literal period, not all periods. The original string remains unchanged; the result is returned as a new string. See MDN’s String.prototype.replace() reference.

Remove every occurrence

For every occurrence of a literal target, use replaceAll():

const text: string = "a-b-c";
const result: string = text.replaceAll("-", "");

console.log(result); // "abc"

Because the target is a string, characters such as ., *, ?, [, and are treated literally rather than as regular-expression syntax. This also makes replaceAll() a straightforward choice when the target comes from a variable.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

To remove every character matching a rule, use a global regular expression instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const withoutDigits = "room 42".replace(/[0-9]/g, "");
console.log(withoutDigits); // "room "

The g flag tells the regular expression to match globally. If you pass a regular expression to replaceAll(), it must include g; for example, text.replaceAll(/-/g, ""). A regular expression without that flag causes replaceAll() to throw a TypeError. MDN documents the behavior and empty-pattern case in its String.prototype.replaceAll() reference.

Remove a character at a particular index

When you know the position, concatenate the part before it with the part after it:

function removeAt(text: string, index: number): string {
  return text.slice(0, index) + text.slice(index + 1);
}

console.log(removeAt("hello", 1)); // "hllo"

This removes the UTF-16 code unit at that index. JavaScript string indices count UTF-16 code units, so an index does not always correspond to one character as a person sees it. For example, some emoji use a surrogate pair, and a displayed accented letter may be made from multiple code points. The MDN String reference explains the distinction between code units and code points.

When a “character” may be more than one unit

For ordinary ASCII text, the methods above usually match the intended character. For arbitrary Unicode text, first decide what “one character” means: a UTF-16 code unit, a Unicode code point, or a user-perceived grapheme cluster. A visible symbol can comprise multiple underlying units or code points.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Avoid relying on text.split("") to remove a visible character safely. An empty separator splits a string into UTF-16 code units, which can break a surrogate pair and does not group grapheme clusters. MDN describes this behavior in its String.prototype.split() reference. If an interface lets users delete one displayed character, use a grapheme-segmentation approach rather than treating slice(i, i + 1) as universally character-safe.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Alternative for removing a literal delimiter

split() followed by join() also removes every occurrence of a literal separator:

const result = "a-b-c".split("-").join("");
console.log(result); // "abc"

This can be useful when you already need the split pieces, but for simple removal replaceAll() states the intent more directly. The Unicode caveat applies to splitting with an empty string, not to using a non-empty literal delimiter this way.

Make a reusable TypeScript helper

If the operation appears in multiple places, give it a descriptive helper name and type its inputs and output:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function removeAll(input: string, target: string): string {
  return input.replaceAll(target, "");
}

const cleaned: string = removeAll("x-x-y", "x");
console.log(cleaned); // "-y"

The type string allows an arbitrary-length target, not exactly one character. If callers must provide a single code point or grapheme, that requirement needs separate validation.

Common mistakes to avoid

  • Expecting replace() with a string to remove every match: use replaceAll() for all literal occurrences.
  • Building a regular expression for a literal target unnecessarily: metacharacters can change the pattern’s meaning. A string target to replaceAll() is literal.
  • Using a regex without g for an all-match operation: a global regex is required for replaceAll(), and replace() also needs a global regex to replace all regex matches.
  • Passing an empty target by accident: replaceAll("", replacement) inserts the replacement between UTF-16 code units. Reject an empty target if that result is not intended.
  • Forgetting to save the return value: strings are not changed in place, so assign or return the result.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.