Replacing the first n occurrances of text
===

Inspired by [this question][1] I thought to write my own jQuery function that would replace the first n occurrences of a particular string.

The code I've written takes a regular expression to search for, a string to replace found instances with, the maximum number of times to make the replacement and, optionally, a selector with which to narrow down the replacements.

It takes the form  
`$.fn.replaceFirstNWith = function(yourregex, replacetext, firstNToReplace, optionalSelector)`

It is called like  
`$("#document").replaceFirstNWith("\\b[Tt]ext\\b", "CARROT", 4);`

This will replace the first 4 instances of the word text (or Text) that are found in the children of the `#document` element with the word CARROT.

Alternatively you can call  
`$("#document").replaceFirstNWith("\\b[Tt]ext\\b", "CARROT", 4, "p");`

Which will replace the first 4 instances of text within `p` elements that are children of `#document`.

The full code and a working fiddle is [here][2].

The code seems to work, but how can I improve it? Even on the relatively small amount of HTML in the fiddle the code it is noticeably slow to run. What optimisations can I make to the code to improve the run time?


  [1]: http://stackoverflow.com/q/11629229/563838
  [2]: http://jsfiddle.net/ohsostupid/vdvuH/1/