开发者

Replace Non exact Needle in Haystack

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.

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;
}

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.

Here is some example text abcfooxyz, that is all.

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.

Here is some example text bar that is all.

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.

Thank you for your assistance.

EDIT: Solution Found

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 flo开发者_高级运维w with rel="noreferrer". Here bdy is the java script documnet.body.innerHTML element.

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

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


Try this:

var match = new RegExp('(\\b)\\w*' + needle + '\\w*(\\b)', 'ig');
haystackText.replace(match, '$1' + replacement + '$2');

Explanation of regex:

\b        word boundary (space, punctuation, etc)
\w*       0 or more alphanumeric characters
[needle]  your text
\w*       0 or more alphanumeric characters
\b        word boundary 


The following will match "foo" surrounded by any number of alphanumeric characters, including zero.

\w*foo\w*
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜