7

I am using Google Apps Script to create apps. I encounter issue when I try to remove whitespaces from my spreadsheet value. I have referred alot of posts & comments in stackoverflow and other forum too. They are all talking about using .replace method. However, .replace method does not work for me.

var ItemArray = <<getValue from google spreadsheet>>
var tValue = ItemArray[0][2].toString();

for (var row = 0; row<ItemArray.length; row++)
{
   var TrimmedStrA = ItemArray[row][2].toString().replace(' ', '');
   var TrimmedStrB = tValue.replace(' ', '');

   if (TrimmedStrA == TrimmedStrB)
   {
      <<other code>>

   } //end if
} //end of loop
caiosm1005
  • 1,686
  • 1
  • 19
  • 31
Calvin Ong
  • 77
  • 1
  • 1
  • 3
  • 1
    This is not trimming. Trim is meant to remove whitespaces from the sides up to the nearest non-whitespace character; not from the entire string. – caiosm1005 Apr 08 '14 at 22:58

2 Answers2

10

A simple RegExp object should be used in the replace() method. \s is a simple solution to find whitespace. The 'g' provides a global match for instances of whitespace:

tValue.replace(/\s/g, "") 

This will get you pretty close without knowing what your data looks like.

.replace() documentation here.

gebond
  • 30
  • 1
  • 5
rGil
  • 3,719
  • 1
  • 22
  • 30
2

You may use split function followed by join. It's very simple to use.

yourString = yourString.split(" ").join("")

It'll remove all spaces no matter where they are located in the stirng.

lockhrt
  • 597
  • 6
  • 11