0

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!

4
  • 1
    I think you want split("/") Commented Aug 31, 2022 at 16:35
  • 2
    String.split is a function, so you should call it with parentheses not brackets. paramCheckDate.split(...) Commented Aug 31, 2022 at 16:35
  • paramCheckDate.split("/").reverse().join(""); I like to use this instead. It is clean. Commented Aug 31, 2022 at 16:42
  • There is another mistake here though, because the source format seems to be M/D/Y and not D/M/Y, so reversing won't yield the desired result. Commented Aug 31, 2022 at 16:44

3 Answers 3

1
  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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Use paramCheckDate.split("/")

Comments

0

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

1 Comment

While this works, it is hard to read and unnecessarily slow (approx. 6x slower than splitting once and then concatenating), so I think with this we would be teaching a bad habit here...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.