Changing a string from user input

RoXes

Having some troubles figuring this one out as I'm not too sure what you'd even call it.

I'm trying to take a users input and swap it around, so for example:

1 input for the date: DD MM YYYY, I want them to input it as such and then change it to YYYYDDMM server side before sending it where it needs to go.

I've tried looking at regex expressions and str replace but it doesn't appear to have an option to pull the end of a users string and place it in a different location. Any insight would be appreciated of where I could find some more help on this or what direction to go in.

CertainPerformance

You can do it with regex if you capture each part of the date string in a group, and then echo the groups back in a different order, without the spaces:

const reformatDate = dateStr => dateStr.replace(/^(\d{2}) (\d{2}) (\d{4})$/, '$3$1$2');
console.log(reformatDate('05 12 2000'));
console.log(reformatDate('10 31 2010'));
console.log(reformatDate('01 01 2018'));

With Javascript's .replace, $ followed by a number in the second parameter passed to the .replace function replaces the $# with that captured group in the regular expression. For example, $3 gets replaced with whatever was matched by the third (...).

The same sort of replacement syntax works in PHP:

function reformatDate($dateStr) {
  return preg_replace('/^(\d{2}) (\d{2}) (\d{4})$/', '$3$1$2', $dateStr);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related