How to replace substring in string in TypeScript?


Sometimes, we need to replace a substring with a new string or any particular character while working with TypeScript. The simple way to replace the substring or part of the string is to use the replace() method.

Here, we will create a custom algorithm to replace the string for the interview purpose of the beginners. However, we will also see the replace() method at last in this tutorial.

Create the Custom Algorithm to Replace the Substring

We will use the for loop to iterate through the main string in this part. We will use the substr() method of the string library to find if the substring at index ‘i’ matches the replaceable string. If the substring at index position ‘i’ matches the replaceable string, we will replace it with a new string.

Syntax

In the syntax below, we have implemented the custom algorithm to replace the part of the string with the new string. We used the substr() method to find the old substring.

function replaceSubString(
   mainString: string,
   oldString: string,
   newString: string
): string {
   let tempString: string = "";
   for (let i = 0; i < mainString.length; i++) {
      if (mainString.substr(i, oldString.length) === oldString) {
         tempString = tempString + newString;
         i = i + oldString.length-1;
      } else {
         tempString = tempString + mainString[i];
      }
   }
   return tempString;
}

Parameters

The above custom function takes three parameters of string type.

  • mainString − It is a string in which we need to replace a string.

  • oldString − It is a substring to be replaced.

  • newString − It is a new string that will be replaced by oldString.

Algorithm

  • Step 1 − Create a function that takes a mainString, oldString, and newString as a parameter and returns a string.

  • Step 2 − Create a tempString variable to store the string after replacing it.

  • Step 3 − Use the for loop to iterate through the string.

  • Step 4 − Get the substring from the ith index of length the same as oldString’s length using the substr() library method.

  • Step 5 − Match the substring with the oldString. If the substring at a position at the ith index matches the oldString, add a new string to tempString.

  • Step 6 − Increase the value of the ‘i’ variable by oldstring’s length - 1.

  • Step 7 − If the substring at the ith index doesn’t match to oldString, add a character from the ith index of the mainString to the tempString.

  • Step 8 − After iteration completes, return the tempString.

Example

In the example below, we have used the mainString to replace a single word with a new one. We have created the custom function named replaceSubstring() function and implemented the above algorithm.

In the output, users can observe that in the mainString, the ‘TypeScript’ word is replaced by the ‘coding’ word.

// define the mainString, oldString, newString
let mainString: string =
"TutorialsPoint is the best website to learn TypeScript!";
let oldString: string = "TypeScript";
let newString: string = "Coding";

// function to replace a substring
function replaceSubString(
   mainString: string,
   oldString: string,
   newString: string
): 
string {
   // create a temporary string
   let tempString: string = "";
   // iterate through the string
   for (let i = 0; i < mainString.length; i++) {
      // get the substring from ith index of length same as oldString's length and compare it with the oldString.
      // If it matches with oldString, add new string to tempstring, and increase i by oldString's length-1.
      if (mainString.substr(i, oldString.length) === oldString) {
         tempString = tempString + newString;
         i = i + oldString.length - 1;
      } 
      else {
         // if substring at index ith position doesn't match, add character from ith index to tempString
         tempString = tempString + mainString[i];
      }
   }
   // return tempString after iteration.
   return tempString;
}
// call the replaceSubString function
console.log("The old string is " + mainString);
console.log("The new string is ");
console.log(replaceSubString(mainString, oldString, newString));

On compiling, it will generate the following JavaScript code −

// define the mainString, oldString, newString
var mainString = "TutorialsPoint is the best website to learn TypeScript!";
var oldString = "TypeScript";
var newString = "Coding";
// function to replace a substring
function replaceSubString(mainString, oldString, newString) {
   // create a temporary string
   var tempString = "";
   // iterate through the string
   for (var i = 0; i < mainString.length; i++) {
      // get the substring from ith index of length same as oldString's length and compare it with the oldString.
      // If it matches with oldString, add new string to tempstring, and increase i by oldString's length-1.
      if (mainString.substr(i, oldString.length) === oldString) {
         tempString = tempString + newString;
         i = i + oldString.length - 1;
      } else {
         // if substring at index ith position doesn't match, add character from ith index to tempString
         tempString = tempString + mainString[i];
      }
   }
   // return tempString after iteration.
   return tempString;
}
// call the replaceSubString function
console.log("The old string is " + mainString);
console.log("The new string is ");
console.log(replaceSubString(mainString, oldString, newString));

Output

The above code will produce the following output −

The old string is TutorialsPoint is the best website to learn TypeScript!
The new string is
TutorialsPoint is the best website to learn Coding!

Using the replace() Method to Replace The Part of The String

The replace method allows us to replace the string's regular expression or a particular word. Also, we can replace all occurrences of the particular substring using the replace() method. We need to invoke it by taking the string as a reference in which we need to make a replacement.

Syntax

Users can follow the syntax below to replace a particular part of the string with a new string.

str.replace(reg_exp, new_str);

Parameters

  • reg_exp − It takes a regular expression as the first parameter to match with the substring.

  • new_str − It is a new string to replace the substring that matches the regular expression.

Example

In this example, we have used the replace() method to replace the particular substring of str with the “sample” string. In the output, users can observe that “demo” is replaced with the “sample.”

// defining the string
let str: string = "This is a demo string!";

// use the replace method to replace the "demo" substring with "sample"
let newString: string = str.replace("demo", "sample");
console.log("The old string is " + str);
console.log("The new String is " + newString);

On compiling, it will generate the following JavaScript code −

// defining the string
var str = "This is a demo string!";

// use the replace method to replace the "demo" substring with "sample"
var newString = str.replace("demo", "sample");
console.log("The old string is " + str);
console.log("The new String is " + newString);

Output

The above code will produce the following output −

The old string is This is a demo string!
The new String is This is a sample string!

We learned the different approaches to replacing a particular part of the string with a new string in this tutorial. Obviouslly, the best way to replace the string is using the replace() method, which also takes the regular expression as a parameter. Still, we should know the basic implementation of the naïve approach to replace the substring.

Updated on: 03-Jan-2023

746 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements