maxime dumont maxime dumont - 5 months ago 13
jQuery Question

Strange behavior with jquery replace in array

i have to change id value in a form to all input and select field.

$(value).find('input, select').each(function() {
var id = $(this).attr('id');
var idArray = id.split("_");
var newId = id.replace(idArray[5], 2);
newId = id.replace(idArray[7], (index + 1));
console.log(newId);
$(this).attr('id', newId);
});


value is the form. the console return the idArray[5] replaced by (index +1)...

Any idea, Thanks

Answer

So you are calling String.prototype.replace as your id is actually a string. And as second argument you are passing an int:

var newId = id.replace(idArray[5], 2);

This will replace whatever is in that string by the number 2 and not by the second index of your array.

Edit

As replacing the parts by numbers is the intended behavior this is what is actually happening:

The replace of idArray[5] which equals 1 is replacing the first 1 character it finds with 2.

The other replace is acting uppon the same origin string (id and not newId) and replacing the same 1 character to the value of (index + 1).

The solution in this case is to manipulate the array and then join it back into a string:

$(value).find('input, select').each(function() {
    var id = $(this).attr('id');
    var idArray = id.split("_");
    idArray[5] = 2;
    idArray[7] = (index + 1);
    var newId = idArray.join('_');
    console.log(newId);
    $(this).attr('id', newId);
});