I have a document where an HTML string contains text with embedded dates. Assuming I can wrap each date in a span and give them the same class, I want a Script in the template that will format all the dates.
This is slightly different than formatting a Date field or fields. I don’t want to replace any values with values out of the Data Model. I want my script to iterate over the class members, extract the html, format the html in a specific date format, and then replace the original date with the formatted date.
On a web page, for example, I could do this:
const collection = document.getElementsByClassName("myDate");
for (let i = 0; i < collection.length; i++) {
myDateSTR = collection[i].innerHTML;
myDate = new Date(myDateSTR).toLocaleDateString('es-US', { day: '2-digit', month: '2-digit', year: 'numeric' })
collection[i].innerHTML = myDate;
What would an equivalent “Standard Script” look like in Connect?
With the script selector set to “.myDate”, and the script scope (under “Options” in the script editor) set to “Each matched element”:
const date = new Date(this.text())
this.text(formatter.date(date, "dd/MM/yyyy"))
Note that I’m calling “text” (which maps to innerText) rather than “html” (which maps to innerHTML) because it is slightly faster and there is no HTML to parse here anyway.
It’s tempting to try this:
const date = new Date(this.text())
this.text(date.toLocaleDateString('es-US', { day: '2-digit', month: '2-digit', year: 'numeric' }))
… but this is unfortunately not supported by the Java-based JS engine we use for standard scripts. The second argument to toLocaleDateString is ignored.
Thank you! The Option to “Each matched element” was the missing piece for me. I did have to change your “const” to a “var” because you cannot redefine constants (which is what happens when you iterate through “Each matched element”).