简体   繁体   中英

splitting a date string by index to string using javascript

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!

Square braces are for array access, round braces are for function calls.

Use paramCheckDate.split("/")

  1. You have ['/'] instead of ('/') - String.prototype.split is a function that you have to call, not an array/object that you have to index.
  2. There is no need for toString() , the parts of the strings are already - well - strings.
  3. 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.)
  4. 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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM