基本上我有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