70

In my angular 5 project, with typescript I am using the .trim() function on a string like this, But it is not removing the whitespace and also not giving any error.

this.maintabinfo = this.inner_view_data.trim().toLowerCase();
// inner_view_data has this value = "Stone setting"

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-4.html This docs clearly say that .trim() is part of the typescript.

What is best way to remove whitespace in from a string in typescript?

void
  • 36,090
  • 8
  • 62
  • 107

3 Answers3

112

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

var out = "hello world".replace(/\s/g, "");
console.log(out);
Wictor Chaves
  • 957
  • 1
  • 13
  • 21
Hrishikesh Kale
  • 6,140
  • 4
  • 18
  • 27
  • It remove all the spaces even between two word, use .trim(), see the detail https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim – Ali Adravi Nov 16 '18 at 16:52
  • 2
    .Trim() is remove white space at the beginning or ending, not all white space. – Omzig Jul 30 '20 at 19:16
15

The trim() method removes whitespace from both sides of a string.

To remove all the spaces from the string use .replace(/\s/g, "")

 this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();
void
  • 36,090
  • 8
  • 62
  • 107
8

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();
Jan Wendland
  • 1,350
  • 9
  • 17