Reputation: 97
I have a method I am using to format the date in a Google Apps Script so that it just reads MMM dd, yyyy
. I am trying to replace all the "-"s in my date string with "" but using the replace method only replaces the first "-" of the string and none of the rest. Any thoughts as to why that is? How can I get it to replace all the "-" in my string?
Here is my code:
function formatDate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheets()[0];
var templateSheet = ss.getSheets()[1];
var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 9);
var data = dataRange.getValues();
var startRow = 2; // First row of data to process
var objects = getRowsData(dataSheet, dataRange);
//Format date in column D
for(var k=0; k<objects.length; k++){
var column = data[k];
var DateCell = column[4];
var emailSent = column[8];
var column = data[k];
var DateCell = column[4];
var date = new Date(DateCell).toLocaleDateString('en-US',{
day : 'numeric',
month : 'short',
year : 'numeric'
}).split("").join("-").replace(/-/g, "");
var Date1 = dataSheet.getRange(startRow + k, 5);
var Date2 = dataSheet.getRange(startRow + k, 6);
Date1.setValue(date);
Date2.setValue(date);
}
}
Upvotes: 1
Views: 12511
Reputation: 5645
Both of these snippets work.
var str = "testing-this-out";
var beforeEl = document.getElementById("before");
var afterEl = document.getElementById("after");
beforeEl.innerText = "Before: " + str;
afterEl.innerText = "After: " + str.replace(/([-])+/g, "");
<p id="before"></p>
<p id="after"></p>
var date = new Date("2017-01-11").toLocaleDateString('en-US',{
day : 'numeric',
month : 'short',
year : 'numeric'
}).split("").join("-").replace(/([-])/g, "");
document.getElementById("date").innerText = date;
<span id="date"></span>
Upvotes: 3