So, I’ve got a string. The string contains html. I’m checking the string for ‘name’, if it doesn’t have one I’m using sneaking one in there if it does I need to change what it is.
var myString = '<input id="accountUser_c967817c993e62b1de50e4f0401a03ae" type="hidden" value="c967817c993e62b1de50e4f0401a03ae" name="addRow[]"><div class="colors goldbluegreenorange"></div>';
if (myString.indexOf('name') == -1) {
myString = myString.substr(0,myString.indexOf('>')) + ' name="addRow[]"' + myString.substr(myString.indexOf('>'));
} else {
//get what's inside name's quotes and change it to removeRow[].
}
I’ve got jquery going on too, if that makes more sense than straight javascript.
Since you’re using jQuery, why not create a jQuery element out of that string, so that we can use jQuery’s beautiful API for this? It’ll make it far less error-prone than raw string manipulation.
Here’s some sample code:
Note: the
vin that function is the current value of thenameattribute, which jQuery automatically passes in to the callback function. The return value is what the value of the attribute should be updated to.Update: If you then want to convert it all back into a string, use this:
Here’s the fiddle: http://jsfiddle.net/kBF3c/