我有这个date1,我想插入" - "使其成为2016-09-23.有谁知道如何使用JavaScript进行此操作?
var date1 = "20160923";
Run Code Online (Sandbox Code Playgroud)
小智 10
你可以使用正则表达式:
var ret = "20160923".replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
console.log(ret);
Run Code Online (Sandbox Code Playgroud)
/)
假设年份是4位数字,而月份和日期是2位数字,则可以使用此代码
var date1 = "20160923";
var formattedDate = date1.slice(0, 4) + "-" + date1.slice(4, 6) + "-" + date1.slice(6, 8);
console.log(formattedDate);
Run Code Online (Sandbox Code Playgroud)
没有直接的方法,您可以编写自己的方法,例如InsertAt(char,pos)
使用 Prototype 对象 [参考资料来自此处]
String.prototype.InsertAt=function(CharToInsert,Position){
return this.slice(0,Position) + CharToInsert + this.slice(Position)
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它
"20160923".InsertAt('-',4); //Output :"2016-0923"
Run Code Online (Sandbox Code Playgroud)