Replace Non exact Needle in Haystack
<p>Hi i have a Javascript function that replaces needle's in a haystack as you will see the haystack is the entire body of the page.</p>

<pre><code>function replace(needle, replacement) {
    haystackText = document.body.innerHTML
    var match = new RegExp(needle, "ig");     
    var replaced = "";
    replaced = haystackText.replace(match, replacement);
    document.body.innerHTML = replaced;
}
</code></pre>

<p>My problem is that the needles im looking for are not exact. For examples sake ill say the needle text is "foo". The text i would want to replace might then look like this.</p>

<pre><code>Here is some example text abcfooxyz, that is all.
</code></pre>

<p>I need to replace abcfooxyz, but all i know what to look for is foo. So if the replacement text was bar i need the output to look like this.</p>

<pre><code>Here is some example text bar that is all.
</code></pre>

<p>I'm sorry if this is obvious i have searched for a solution but javascript is not my native language however im forced to use it for the implementation of this app. I can use jQuery but i would prefer not to as i have not yet called the library and i do not know it well.</p>

<p>Thank you for your assistance.</p>

<p><strong>EDIT: Solution Found</strong></p>

<p>Ok so after some additional reading and experimentation with RegExp i have written a separate function to deal with URL's in side a a href html tag. This is used to redirect users who click outbound links to a warning page before continuing and stopping refferal and page rank data flow with rel="noreferrer". Here bdy is the java script documnet.body.innerHTML element.</p>

<pre><code>function linkreplace(link, bdy) {
    haystackText = bdy;
    var replacement = 'a href=\"http://mysite.com/outbound_refer.php?link=' + link + '\" rel=\"noreferrer\"';
    var match = new RegExp('[^\\&lt;\\&gt;]*' + link + '[^\\&gt;\\&lt;]*', 'ig');
    replaced = haystackText.replace(match, replacement);
    return replaced;
}
</code></pre>

<p>Here RegExp finds the needle text and includes all text within the HTML Tag until it find the tag open and close. Here \&lt; and \> set the expression to look for special characters of &lt; and > so &lt;> in regular text wont match. The ^ sets the Expression to match all characters except for the ones in the brackets. </p>
