Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character in string using javascript [duplicate]

Tags:

javascript

I have this date1, I want to insert "-" to make it 2016-09-23. Is anyone know how to do this using javascript?

var date1 = "20160923";
like image 642
AyDee Avatar asked Oct 29 '25 09:10

AyDee


2 Answers

You can use regex:

var ret = "20160923".replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
console.log(ret);

/)

like image 93
velen Avatar answered Oct 30 '25 23:10

velen


Given that the year is 4 digit and month and day are 2 digit you can use this code

var date1 = "20160923";

var formattedDate = date1.slice(0, 4) + "-" + date1.slice(4, 6) + "-" + date1.slice(6, 8);

console.log(formattedDate);
like image 28
Weedoze Avatar answered Oct 30 '25 23:10

Weedoze