Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Apps Script - remove spaces using .replace method does not work for me

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
like image 349
Calvin Ong Avatar asked May 14 '13 15:05

Calvin Ong


People also ask

How do I delete a range of cells in Google script?

To clear a range's contents, first reference the range and then use the clearContent() method. The range's contents have been cleared but its formatting has been preserved.

How do I create an auto clear script in a Google spreadsheet?

Goto Run & select Run function and then select clearRange. Once you have run the script, your spreadsheet should be cleared.


2 Answers

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.

t.Value.replace(/\s/g, "") 

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

.replace() documentation here.

like image 140
rGil Avatar answered Nov 07 '22 15:11

rGil


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.

like image 25
lockhrt Avatar answered Nov 07 '22 16:11

lockhrt