Bruno Eduardo Rosselli
Bruno Eduardo Rosselli

Reputation: 167

How to change word order from within a string?

I have a string that returns from my Backend: startDate: "September 28, 2021" in the format: mm-dd-yyyy. I need to format this string in Front to display: yyyy-mm-dd ie: 2021, September 28.

How do I format a string and change the order of the words contained in it?

Upvotes: 0

Views: 466

Answers (3)

Will Alexander
Will Alexander

Reputation: 3571

RegEx works, but if you want to be able to read and understand the code:

const input = 'September 28, 2021';
const [month, day, year] = input.split(' ');
const formattedDate = `${year}, ${month} ${day.replace(',', '')}`

Upvotes: 0

AR. Arif
AR. Arif

Reputation: 63

Here is the easy one that will also validate your date too

let date = new Date("September 28, 2021");
let month = date.toLocaleString("default", { month: "long" });

let fomattedDate = `${date.getFullYear()}, ${month} ${date.getDate()}`;

console.log(fomattedDate);

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522516

You could use a regex replacement here:

var input = "September 28, 2021";
var output = input.replace(/\b(\w+ \d{1,2}), (\d{4})\b/, "$2, $1");
console.log(input);
console.log(output);

Regarding the choice of regex pattern I used, it should be sufficient and safe assuming that nothing else in your text would be a word followed by a 1-2 digit number, comma, then a 4 digit number.

Upvotes: 2

Related Questions