简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM