TypeScript string replace() method explanation with example

TypeScript string replace() method explanation with example:

replace method of string is used to replace a substring in a string. This is an inbuilt method and we can use it with a string in typescript.

In this post, I will show you how to use the replace() method with an example:

Syntax of replace():

replace is defined as below:

string.replace(subStr, newStr[, flags])

Here,

  • subStr is the substring that needs to be replaced. Also, we can pass one regular expression as this parameter. It will replace all substrings that matches with the regular expression.
  • newStr is the new string that we need to replace with the old string.
  • flags is an optional parameter. This parameter is a string holding the combination of regular expression flags.

This method returns the newly created string.

Example of replace:

Let’s take a look at the below program:

let givenString = 'Hello World'

let newStr = givenString.replace('World', 'Universe')

console.log(newStr)

Here,

  • givenString is the original string.
  • Using replace, we replaced World with Universe.
  • The result is stored in newStr.

It will print:

Hello Universe

Note that it replaces the first occurrence of the word:

let givenString = 'Hello World World'

let newStr = givenString.replace('World', 'Universe')

console.log(newStr)

It will print:

Hello Universe World

Example of replace with regex:

We can also use regex with replace as like below:

let givenString = 'Hello World 123'

let newStr = givenString.replace(/[0-9]/, '*')

console.log(newStr)

It will replace 1 with *.

Hello World *23

You might also like: