typescriptangular5typescript2.0c#-6.0

What's the StringBuilder equivalent in TypeScript?


So I have this string that contains a percentage symbol %. I want to be able to replace it with the # symbol using TypeScript. I am still learning TypeScript so its syntax is still throwing me off. I managed to implement the solution that I need in C# and that piece of code can be found below:

public static void Main(string[] args)
{
    string data = "AHu%odk"; // The % character will always be at index 3
    string finalResult = "";
    if (data.Contains("%"))
    {
        StringBuilder sbFirstIndex = new StringBuilder(data);
        sbFirstIndex[3] = '#';
        finalResult = sbFirstIndex.ToString();
        Console.WriteLine("Appended string now looks like this: {0} \n", finalResult);
    }
    else
    {
        Console.WriteLine("False. It does not contain it");
    }
}

Here is my TypeScript implementation but I got stuck if checking for the index of the character:

changePercantage(input: string): void {
    var data = "AHu%odk";
    var finalResult = "";
    var index = result.indexOf("%");

    if (index == 3) {
        // Replace the percentage with the # character
    }
}

The version of TypeScript that I am using is 2.3.3.0.

Angular: 5.0.0

Node.js: 8.9.3

Npm: v5.6.0


Solution

  • In TypeScript, for string replacement, use a regular expression:

    function changePercentage(input) {
        return input.replace(/%/, "#");
    }
    
    console.log(changePercentage("AHu%odk"));