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(****-**-**)
?
Asked
Active
Viewed 487 times
2

Karina Shulan
- 161
- 1
- 9
-
3you could have a look [here](https://stackoverflow.com/questions/45031441/masking-a-string/45031815#45031815). – Nina Scholz Apr 04 '22 at 13:51
-
2`'20220112'.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')` – k102 Apr 04 '22 at 13:56
-
Is that really a number? Or rather a string that contains only digits? – Bergi Apr 04 '22 at 13:58
-
@Bergi It's a number – Karina Shulan Apr 04 '22 at 14:01
-
2Then start with `.toString(10)`, check that it's really an 8-digit number, and do ordinary string operations on that. There's no builtin `pattern` function or something that would do this for you. – Bergi Apr 04 '22 at 14:02
1 Answers
2
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") )

Maik Lowrey
- 15,957
- 6
- 40
- 79