remove a character from a string in typescript

To remove a specific character from a string in typescript, we can use the splice method available in javascript. Here's the code for the same:

let str: string = "example";
let charToRemove: string = "m";
let index: number = str.indexOf(charToRemove);

if (index !== -1) {
  str = str.splice(index, 1);

console.log(str); // outputs "exaple"
200 chars
10 lines

In the code above, we first declare a string str and a character charToRemove that we want to remove from the string. We then find the index of the first occurrence of the character in the string using the indexOf method.

If the index is found (i.e., the character is present in the string), we use the splice method to remove the character from the string. Finally, we print the modified string to the console using console.log.

Note that the splice method returns an array of the removed elements, which in this case is an array with a single element (the character we wanted to remove). To get the modified string, we simply assign the result of the splice method back to the str variable.

gistlibby LogSnag