0

I have to format a date, but said date is inside a template literal, I cannot create a variable outside, and format it before, I think, since it is inside of a map function:

$.getJSON(  base_url + '/xxx/wp-json/wp/v2/news?housing_type' + id, posts => { 
    $('.page__content__news__inner-wrap').html(`
        ${posts.map( item =>
            `<div class="news__item"><a href="${item.news_url}" class="news__item__link" target="_blank"><p class="news__item__date">${item.date}</p><h3 class="news__item__title">${item.title.rendered}&nbsp;&nbsp;</h3></a></div>`)}
    `);
});

What I need to do is to display this part:

${item.date}

With a specific format, something like this (which of course doesn't work):

${item.date}.format("mmmm d, yyyy")

Is there a way to add ${item.date} to a variable in this scenario so I can format it?

Sergi
  • 1,192
  • 3
  • 19
  • 37
  • 3
    Everything inside the `${}` can be javascript. So long as it results in a value returned. Given that, `format()` can be put inside it as well. For instance: `\`Your name is ${'me'.toUpperCase()}\`` is perfectly valid. – Taplar Apr 25 '19 at 18:18
  • I have tried ${item.date.format("mmmm d, yyyy")} but it doesn't work, how could I do it? – Sergi Apr 25 '19 at 18:53
  • Are you sure that `item.date` is a Date object? – Taplar Apr 25 '19 at 18:54
  • No, it's a simple string. it's JSON, look at the full function above...So I guess I should parse it first. – Sergi Apr 25 '19 at 18:56
  • Well, both `String.prototype.format` and `Date.prototype.format` do not exist. So it looks like you're using the wrong method either way. – Taplar Apr 25 '19 at 18:58
  • 1
    [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Taplar Apr 25 '19 at 18:59
  • 1
    You may want to consider not nesting string templates like that; it can make the code hard to read. Note that calling `html()` with an array of strings automatically joins them. – Heretic Monkey Apr 25 '19 at 19:08

0 Answers0