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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
