How to create pattern for numbers

Viewed 262

there. I have a number 20220112 which i need to convert this number to string which will look like this 2022-01-12 Maybe anone knows is there are some patterns in JS which i could use for easy convertation?
Something like const date = patetn(****-**-**) ?

1 Answers

Write a function where you first cast the passed value to a string. then you can format the string to your pattern.

function formatNumber(num) {  
    return String(num).replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
}

console.log('formatted: ', formatNumber("20220401") )

Related