2016-01-25 57 views
2

我的投入,像這樣的名稱替換第一個方括號中的數值:的JavaScript的name屬性

<input class="serialize" name="day[0][0]" /> 
<input class="serialize" name="event[0][0][0][0]" /> 

我想要做的是更換第一個夾子的字符(天[] [0],事件[] [0] [0] [0])...但是在夾具中的人物可以改變...

這裏是第一代碼草案

jQuery(this).find('.serialize').each(function(index) { 

    var attr = jQuery(this).attr('name'); 
    attr = attr.replace('regex magic'); // This line is the problem 
    jQuery(this).attr('name', attr); 

}); 
+0

因爲數組鍵可以改變...這將打破取代 –

+0

你需要只替換第一個'['之後的第一個字符,或者它可以是多個字符,直到關閉']'? –

回答

4

.attr() method接受函數,因此您不需要手動遍歷每個元素,檢索name屬性並更新它。

可以只傳遞一個函數,並返回替換屬性:

$('.serialize').attr('name', function() { 
    return this.name.replace(/^(\w+)\[.*?\]/, '$1[20]'); 
}); 

表達/^(\w+)\[.*?\]/後的一個或多個\w字符(其然後採集,再替換)將選擇所述第一組括號。

這將返回:

<input class="serialize" name="day[20][0]"> 
<input class="serialize" name="event[20][0][0][0]"> 

作爲一個側面說明,\w+將符合下列字符中的一個或多個:[a-zA-Z0-9_]。如果角色不同,你可能要使用:

$('.serialize').attr('name', function() { 
    return this.name.replace(/^(.*?)\[.*?\]/, '$1[20]'); 
}); 

另外,如果您想更新的第一套基於索引支架的價值,你可以使用:

$('.serialize').attr('name', function (i) { 
    return this.name.replace(/^(\w+)\[.*?\]/, '$1[' + i + ']'); 
}); 

這將返回:

<input class="serialize" name="day[0][0]"> 
<input class="serialize" name="event[1][0][0][0]"> 
<input class="serialize" name="somethingelse[2][0][0][0]"> 
+0

但是這也會刪除數組的名稱:''proof [0] [0]「。replace(/^\ w + \ [。*?\] /,」[20]「)'會輸出'[20 ] [0]'! – elTomato

+1

曼多麼優雅的解決方案。你是忍者;) –