Start learning free

LESSON 69 OF 675 · STRINGS I

String Replace in TypeScript

Lesson

In TypeScript, you can replace part of a string using the replace() method:

s.replace(old, new)      // replaces first occurrence
s.replaceAll(old, new)   // replaces all occurrences

Here are some examples:

let sentence = "I love cats";
let result = sentence.replace("cats", "dogs");
console.log(result);  // I love dogs

let text = "aaa";
console.log(text.replace("a", "b"));     // baa  (only first!)
console.log(text.replaceAll("a", "b"));  // bbb

replace() returns a new string — the original is not modified.


Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign it to result.

STEP 1 OF 1
    Ctrl + Enter to check