I have found the following expression which is intended to modify the id of a cloned html element e.g. change contactDetails[0]
to contactDetails[1]
:
var nel = 1;
var s = $(this).attr(attribute);
s.replace(/([^\[]+)\[0\]/, "$1["+nel+"]");
$(this).attr(attribute, s);
I am not terribly familiar with regex, but have tried to interpret it and with the help of The Regex Coach however I am still struggling. It appears that ([^\[]+)
matches one or more characters which are not '[
' and \[0\]/
matches [0]
. The /
in the middle I interpret as an 'include both', so I don't understand why the author has even included the first expression.
I dont understand what the $1 in the replace string is and if I use the Regex Coach replace functionality if I simply use [0] as the search and [1] as the replace I get the correct result, however if I change the javascript to s.replace(/\[0\]/, "["+nel+"]");
the string s remains unchanged.
I would be grateful for any advice as to what the original author intended and help in finding a solution which will successfully replace the a number in square brackets anywhere within a search string.