基本上我有8个数字组成的简单格式化日期输出这样的日期:Javascript来插入输出数字“/”格式化
<div class="date">20170822</div>
,并寻找一个简单的JS/jQuery脚本插入“/”第4和第6位后,使其:
<div class="date">2017/08/22</div>
感谢,感谢所有帮助:)
基本上我有8个数字组成的简单格式化日期输出这样的日期:Javascript来插入输出数字“/”格式化
<div class="date">20170822</div>
,并寻找一个简单的JS/jQuery脚本插入“/”第4和第6位后,使其:
<div class="date">2017/08/22</div>
感谢,感谢所有帮助:)
的/
字符需要插入字符集。 JavaScript数组有一个.splice()
做这种事情的方法,但字符串不是真正的数组,它们是“数组式”的对象。但是,它们可以非常容易地转换为真正的数组。
从MDN:
阵列状物体
slice
方法也可以叫阵列状物体/ 集合转换成一个新的数组。您只需将该方法绑定到该对象。 函数内部的参数是'类似数组 对象'的示例。
一旦做到这一点,在Array.splice()方法就能解决问题。
var divs = document.querySelectorAll(".date"); // Get all the divs into a node-list (array-like object)
// Convert the node list to an array (so Array.forEach can be used) and loop over the array
[].slice.call(divs).forEach(function(d){
var sAry = [].slice.call(d.textContent); // Convert the text content of the div to an array
// Insert the/at the index positions
sAry.splice(4,0,"/");
sAry.splice(7, 0, "/");
d.textContent = sAry.join(""); // Update the div with the formatted value
});
<div class="date">20170822</div>
<div class="date">20170822</div>
<div class="date">20170822</div>
<div class="date">20170822</div>
<div class="date">20170822</div>
<div class="date">20170822</div>
您可以使用简单的JS这样做
$(document).ready(function(){
$(".date").each(function(i,elem) {
var divdate = $(this).html();
var lenght = divdate.length;
var newdate = '';
for(var i = 0;i<lenght;i++){
if(i==3){
newdate += divdate[i] +'/';
}
else
if(i==5){
newdate += divdate[i] +'/';
}
else{
newdate += divdate[i];
}
}
$(this).html(newdate);});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="date">20170822</div>
<div class="date">20191229</div>
<div class="date">20161025</div>
<div class="date">20150620</div>
您可以使用正则表达式像 "20170822".replace(/^([0-9]{4})([0-9]{2})([0-9]{2})/, "$1/$2/$3");
var els = document.querySelectorAll(".date");
els.forEach(function(el){
var d = el.innerHTML;
el.innerHTML= d.replace(/^([0-9]{4})([0-9]{2})([0-9]{2})/, "$1/$2/$3");
});
<div class="date">20170822</div>
<div class="date">20170102</div>
<div class="date">20170408</div>
<div class="date">20170310</div>
谢谢,很好地工作,但只在第一个div上,我有8个,你可以在同一页面上添加对serveral div的支持吗? – Lawyer
是的!现在编辑示例,querySelector采用第一个节点,使用querySelectorAll:https://codepen.io/cbertelegni/pen/EwgGKb?editors=1111 '''var els = document.querySelectorAll(“。date”); ([0-9] {2})(()()()()() [0-9] {2})/,“$ 1/$ 2/$ 3”); }); ''' – cbertelegni
@Lawyer查看我的更新答案,了解处理所有日期的方法。 –
你尝试过这么远吗?看看[游览]和[问]。 –
你应该显示你试图让我们知道你至少试图研究的代码。你可以在这里做的是使用子字符串。 – schylake
您是否尝试过使用[slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)方法? – Ammar