Javascript 使用javascript在字符串中插入字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39790102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert character in string using javascript
提问by AyDee
I have this date1, I want to insert "-" to make it 2016-09-23. Is anyone know how to do this using javascript?
我有这个 date1,我想插入“-”使其成为 2016-09-23。有谁知道如何使用 javascript 做到这一点?
var date1 = "20160923";
回答by velen
You can use regex:
您可以使用正则表达式:
var ret = "20160923".replace(/(\d{4})(\d{2})(\d{2})/, "--");
console.log(ret);
/)
/)
回答by Weedoze
Given that the year is 4 digit and month and day are 2 digit you can use this code
鉴于年份是 4 位数字,月份和日期是 2 位数字,您可以使用此代码
var date1 = "20160923";
var formattedDate = date1.slice(0, 4) + "-" + date1.slice(4, 6) + "-" + date1.slice(6, 8);
console.log(formattedDate);
回答by Jaydip Jadhav
There is no direct method for this, you can write your own Method like InsertAt(char,pos)
using Prototype object [References from here]
对此没有直接的方法,您可以像InsertAt(char,pos)
使用 Prototype 对象一样编写自己的方法[References from here]
String.prototype.InsertAt=function(CharToInsert,Position){
return this.slice(0,Position) + CharToInsert + this.slice(Position)
}
Then use it like this
然后像这样使用它
"20160923".InsertAt('-',4); //Output :"2016-0923"
回答by Chukwuemeka Onyenezido
Assuming date1 is always consistent...
假设 date1 始终一致...
var date2 = date1.slice(0, 4) + '-' + date1.slice(4, 6) + '-' + date1.slice(6, 8);