0

I am trying to make this work for my page, but I need to understand the regular expression replacement. Can someone break this down for me?

function add_fields(link, association, content) {
    var new_id = new Date().getTime();
    var regexp = new RegExp("new_" + association, "g")
    $(link).parent().before(content.replace(regexp, new_id));
}

I understand the first line (var new_id = ...) and why it is needed, but what is the second line doing, and how does the id replacement work?

I am asking because in my app, when clicking "add_new_row", the new row is inserted at the top of my page, not in the table where it belongs.

Thanks for any help you can offer.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337

1 Answers1

0

The line

    var regexp = new RegExp("new_" + association, "g")

simply creates a RegExp object, which represents a matchable pattern. (Internally, it "compiles" the pattern so that, for example, if it were being matched against repeatedly, it would have done everything it needed to do only once, in advance, so that subsequent uses are more efficient.) The "g" is a flag standing for "global" that means, "Replace all matches." I'm not sure what association is, but that pattern will match "new_<association>".

The next line

$(link).parent().before(content.replace(regexp, new_id));

makes use of the pattern: replace all instances of the above pattern with the generated and unique, datetime-based id. Finally, the content is placed ahead of all its sibling nodes via before.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • Thank you Andrew - this helps. The "association" variable is the name of my sub-model - for example, I may have a model for Orders, which may have many "Line Items" - in this case, the association would be a string containing the name "LineItems". I needed also to change the next line to this: – user1904869 Jun 17 '13 at 13:15
  • $(".DataRow").after(content.replace(regexp, new_id)); This places the inserted row after my last data row. Now this part is working as I intended. I still need to work out some rails functionality to make this work when the user clicks the link, rather than when the page loads. – user1904869 Jun 17 '13 at 13:24