Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
communitycreator

How to replace a substring in a string in TypeScript

Theodore Kelechukwu Onyejiaku

Overview

The replace() method can be used in a TypeScript string to replace a particular substring or a match (regular expression) in a string. All we need to do is pass the substring or regular expression of the substring we want to replace.

Syntax

string.replace(substring|regex, replacement)  
syntax for replace() method in TypeScript

Parameters

  • substring: This is the substring of a string string that we want to replace.
  • regex: This is used as a regular expression to match the substring we want to replace.
  • replacement: This is what we want to use as a replacement to the regex or substring.

Return value

The value returned is a new string.

Example

export {}

// create some strings
let name:string = "Onyejiaku Doe"
let role:string = "Musician"
let language:string = "JavaScript Language"

// create some replacements
let rep1 = "Theodore"
let rep2 = "Author"
let rep3 = "TypeScript"

// replace some substrings
console.log(name.replace("Doe", rep1))
console.log(role.replace(/Musician/gi, rep2))
console.log(language.replace("JavaScript", rep3))
Replace some substrings of a string in TypeScript using replace()

Explanation

  • Line 1: We export our file as a module to prevent scope errors due to the names of variables and keywords.
  • Lines 4–6: We create some strings.
  • Lines 9–11: We create our replacements. These are the strings we will use to replace some substrings in the strings we created.
  • Lines 14–16: Using the replace() method, we replace some substrings and print the new strings to the console.

RELATED TAGS

typescript
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring