How to Replace Characters in a String in TypeScript

A client’s order export had dates like 10-28-2026, and the import tool wanted slashes. I fixed it with a TypeScript string replace, but my first try changed only one dash.

That’s the trap: replace() with a plain string swaps the first match only, and it returns a new string instead of editing the old one.

Quick answer: use replaceAll() (or a regex with the g flag) to change every match, and assign the result:

const note = "Ships 10-28-2026";
const fixed = note.replaceAll("-", "/"); // "Ships 10/28/2026"

Everything below ran under TypeScript 7.0.2 and Node.js v22.22.2 in strict mode, and I use one sample string the whole way.

How does replace() change a character in a TypeScript string?

Here’s the sample, an order note with a dashed date. I printed the result and the original:

const note = "Order 4821 ships 10-28-2026 to Austin, TX.";

const fixed = note.replace("-", "/");
console.log(fixed);
console.log(note); // the original is unchanged

let sku = "TX_4821_BLUE";
sku = sku.replace("_", "-");
console.log(sku);

Output:

Order 4821 ships 10/28-2026 to Austin, TX.
Order 4821 ships 10-28-2026 to Austin, TX.
TX-4821_BLUE
VS Code editor with TypeScript replace() calls on an order note and a SKU, terminal showing only the first dash replaced and the original string unchanged
Only the first dash became a slash, and the original note still prints with both dashes.

Strings in JavaScript are immutable, so you always work with the returned value. For the reverse job of deleting a character, see removing a character from a string in TypeScript.

How do you replace every occurrence in a TypeScript string?

Same order note, now with every dash replaced three ways:

const note = "Order 4821 ships 10-28-2026 to Austin, TX.";

console.log(note.replaceAll("-", "/"));       // ES2021+
console.log(note.replace(/-/g, "/"));         // global regex
console.log(note.split("-").join("/"));       // oldest way

const sku = "TX_4821_BLUE_XL";
console.log(sku.replaceAll("_", " ").toLowerCase());

Output:

Order 4821 ships 10/28/2026 to Austin, TX.
Order 4821 ships 10/28/2026 to Austin, TX.
Order 4821 ships 10/28/2026 to Austin, TX.
tx 4821 blue xl
VS Code terminal showing replaceAll, a global regex and split join each turning 10-28-2026 into 10/28/2026
All three lines print 10/28/2026, and the SKU turns into tx 4821 blue xl.

I’d pick replaceAll() for plain text since it reads best. It needs ES2021, though. With an older lib setting, the compiler stops you:

const note = "Order 4821 ships 10-28-2026 to Austin, TX.";
console.log(note.replaceAll("-", "/"));

Compiler output with –lib es2020:

replace_lib.ts(2,18): error TS2550: Property 'replaceAll' does not exist on type '"Order 4821 ships 10-28-2026 to Austin, TX."'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2021' or later.

Set "lib" (or "target") to es2021 or later in tsconfig.json, or use the /-/g regex. The same split trick powers splitting a string with multiple separators.

How do you replace characters with a regex in TypeScript?

A regex targets a whole set of characters at once. These four patterns cover most of my client work:

const note = "Order 4821 ships 10-28-2026 to Austin, TX.";

// 1. Character class: any of - . , becomes a space
console.log(note.replace(/[-.,]/g, " "));

// 2. Mask every digit in a phone number
console.log("(202) 555-0191".replace(/\d/g, "*"));

// 3. Capture groups: MM-DD-YYYY to YYYY-MM-DD
console.log("10-28-2026".replace(/(\d+)-(\d+)-(\d+)/, "$3-$1-$2"));

// 4. Replacer function: capitalize each word
const city = "san antonio, tx";
console.log(city.replace(/\b\w/g, (c) => c.toUpperCase()));

Output:

Order 4821 ships 10 28 2026 to Austin  TX 
(***) ***-****
2026-10-28
San Antonio, Tx
VS Code editor with four TypeScript regex replace examples, terminal showing punctuation turned to spaces, a masked phone number, a reordered date and capitalized city words
Punctuation becomes spaces, the phone digits are masked, the date is reordered and each word is capitalized.

The phone line prints (***) ***-****, so the parentheses and dash survive. For pulling text out instead of swapping it, read getting a string between two characters in TypeScript.

Common errors when replacing characters in TypeScript

To change one position, you might assign to an index. TypeScript blocks it because strings are read-only, so you rebuild the string with slice() instead:

let code = "ORD-4821";
code[3] = "_"; // strings are immutable

code = code.slice(0, 3) + "_" + code.slice(4);
console.log(code);

Compiler output:

replace_readonly.ts(2,1): error TS2542: Index signature in type 'String' only permits reading.
VS Code showing TypeScript error TS2542 Index signature in type String only permits reading on code[3] assignment
VS Code underlines code[3] and the build fails with TS2542 before any JavaScript is written.

When you know the position instead of the character, the slice() fix above is the pattern to reuse. If you only need the part after a marker, getting the string after a character is simpler.

You’ll also run into these three in code reviews:

let sku = "TX_4821_BLUE";
sku.replace("_", "-");                 // result thrown away
console.log("1:", sku);

try {
  console.log(sku.replaceAll(/_/, "-")); // no g flag
} catch (e) {
  console.log("2:", (e as Error).message);
}

const promo = "Promo: CODE";
console.log("3:", promo.replace("CODE", "$&-2026"));
console.log("4:", promo.replace("CODE", () => "$&-2026"));

Output:

1: TX_4821_BLUE
2: String.prototype.replaceAll called with a non-global RegExp argument
3: Promo: CODE-2026
4: Promo: $&-2026
  • Ignored result: line 1 still has the underscore, so assign it back.
  • Missing g flag: replaceAll() with a non-global regex throws a TypeError at runtime, not at compile time.
  • Special $ patterns: $& means “the match”. Pass a function when the replacement is user text.

Cleaning up whitespace or quote marks is the same idea; see removing spaces from a string in TypeScript.

More string clean-up guides:

Frequently asked questions

How do I replace a character in a string in TypeScript?

Call text.replace("a", "b") and assign the result. It swaps the first match only.

How do I replace all occurrences in TypeScript?

Use replaceAll() with ES2021 or later, or replace() with a regex and the g flag.

Why does TypeScript say replaceAll does not exist?

Your lib or target is older than ES2021. Raise it in tsconfig.json to fix error TS2550.

Does replace() change the original string?

No. Strings are immutable, so replace() returns a new string and leaves the original alone.

Can I replace multiple different characters at once?

Yes. Use a character class like /[-.,]/g, or a replacer function when each character needs its own value.

Where is replace() documented?