Hi I have a few syntax problems as I build a date from a string that looks like
My code :
paramCheckDate = "01/14/2022"
CheckDateYYYYMMDD = paramCheckDate.split["/"][2].toString() paramCheckDate.split["/"][1].toString() paramCheckDate.split["/"][0].toString()
I would like to build another string in the format YYYYMMDD. Splitting by index and then .toString but I have syntax errors if I can get some guidance that would be awesome!
CodePudding user response:
Square braces are for array access, round braces are for function calls.
Use paramCheckDate.split("/")
CodePudding user response:
- You have
['/']
instead of('/')
-String.prototype.split
is a function that you have to call, not an array/object that you have to index. - There is no need for
toString()
, the parts of the strings are already - well - strings. - Your example shows that you want to convert MM/DD/YYYY to YYYYMMDD, however (assuming you fixed #1) you are actually converting it to YYYYDDMM. You'd have to use the third, then the first and then the second part. (I am assuming MM/DD/YYYY as source because there is no 14th month of the year.)
- It would be more performant (and easier to read) not to call
split
3 times. Instead, you can split it once and then join:
const [m, d, y] = paramCheckDate.split('/')
const CheckDateYYYYMMDD = y m d
CodePudding user response:
You can use the below Regular Expression to replace your source string to your required format
const CheckDateYYYYMMDD = paramCheckDate.replace(/(\d )\/(\d )\/(\d )/,"$3$1$2");