How to use replace() method In Typescript

The replace() method with the (‘ / /g) replaces all the occurnces of spaces within an empty string, which elimiates the spaces from the original string.

Syntax:

let outputString: string = inputString.replace(/ /g, '');

Example: The below example removes spaces from the inputString using the replace(/ /g, ”) method.

Javascript
let inputString: string = "Geeks for Geeks";
let outputString: string = inputString.replace(/ /g, "");
console.log(outputString);

Output:

w3wiki

How to Remove Spaces from a String in TypeScript ?

Typescript allows us to remove the spaces between the characters or the entire words of the string. The combination of various inbuilt functions can be implemented to remove the spaces from the string. In Typescript, removing spaces from a string can be done using various approaches which are as follows:

Table of Content

  • Using split() and join() methods
  • Using replace() method
  • Using RegExp
  • Using filter() method
  • Using trim() method
  • Using for loop

Similar Reads

Using split() and join() methods

The split() method mainly divides the string into the array of substrings and join(‘ ‘) then concatenates the substrings by removing the spaces from the string....

Using replace() method

The replace() method with the (‘ / /g) replaces all the occurnces of spaces within an empty string, which elimiates the spaces from the original string....

Using RegExp

The regular expression with the replace() method replaces one ore more whitespace characters with an empty string by removing the spaces from the original string....

Using filter() method

The filter() method along with split() and join(‘ ‘) method constructs the new array of characters by exclusing the spaces. Using the join(‘ ‘) method the charcaters are contatenated back into the single string....

Using trim() method

The trim() method removes whitespace from both ends of a string. To remove spaces from within the string, we can combine trim() with replace()....

Using for loop

In this approach we use a for loop to iterate over the characters of the input string. For each character we check if it is not equal to a space character ‘ ‘. If the character is not a space we will append it to the result string....