Perik Onti
Perik Onti

Reputation: 303

Changing Text (outside of HTML-Tags) to links

I want to have a javascript, that searches for a regex (lets say "abcabc") on a page and replaces that regex with a link.

My try by now was:

function replText(text) {
    var exp = new RegExp("(abcabc)", "g");

    return text.replace(exp, "<a href=\"http://my_site.com/$1\">$1</a>"); 
}


// http://stackoverflow.com/questions/5494259/jquery-change-all-elements-text
// Thanks to Box9!
function recursiveReplace(node) {
    if (node.nodeType == 3) { // text node
        node.nodeValue = replText(node.nodeValue);
    } else if (node.nodeType == 1) { // element
        $(node).contents().each(function () {
            recursiveReplace(this);
        });
    }
}

recursiveReplace(document.body);

Which... kind of works. But then again, not really since it doesn't create links, but rather creates <a href=" -like Strings (with escaped HTML-Entities).

I may use Jquery, but Im not an expert to that. May anyone have a clue how that could be done? I don't want to have it replaced in HTML-Tags (like 'class="abcabc"' and so on).

Thanks in advance!

Upvotes: 0

Views: 165

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

Try

var exp = new RegExp("(abcabc)", "g");
function replText(text) {   
    return text.replace(exp, "<a href=\"http://my_site.com/$1\">$1</a>"); 
}


// http://stackoverflow.com/questions/5494259/jquery-change-all-elements-text
// Thanks to Box9!
function recursiveReplace(node) {
    if (node.nodeType == 3) { // text node
        $(node).replaceWith(replText(node.nodeValue))
    } else if (node.nodeType == 1) { // element
        $(node).contents().each(function () {
            recursiveReplace(this);
        });
    }
}

recursiveReplace(document.body);

Demo: Fiddle

Upvotes: 3

Related Questions