Search code examples
stringreplacefindhref

Find and replace text and wrap in "href"


I am trying to find specific word in a div (id="Test") that starts with "a04" (no case). I can find and replace the words found. But I am unable to correctly use the word found in a "href" link.

I am trying the following working code that correctly identifies my search criteria. My current code is working as expected but I would like help as i do not know how to used the found work as the url id?

var test = document.getElementById("test").innerHTML
function replacetxt(){
    var str_rep = document.getElementById("test").innerHTML.replace(/a04(\w)+/g,'<a href="">TEST</a>');
    var temp = str_rep;
    //alert(temp);
    document.getElementById("test").innerHTML = temp;
}

I would like to wrap the found word in an href but i do not know how to use the found word as the url id (url.com?id=found word).

Can someone help point out how to reference the found work please?

Thanks


Solution

  • If you want to use your pattern with the capturing group, you could move the quantifier + inside the group or else you would only get the value of the last iteration.

    \ba04(\w+)
    
    • \b word boundary to prevent the match being part of a longer word
    • a04 Match literally
    • (\w+) Capture group 1, match 1+ times a word character

    Regex demo

    Then you could use the first capturing group in the replacement by referring to it with $1

    If the string is a04word, you would capture word in group 1.

    Your code might look like:

    function replacetxt(){
        var elm = document.getElementById("test");
        if (elm) {
            elm.innerHTML = elm.innerHTML.replace(/\ba04(\w+)/g,'<a href="url.com?id=$1">TEST</a>');
        }
    }
    
    replacetxt();
    <div id="test">This is text a04word more text here</div>

    Note that you don't have to create extra variables like var temp = str_rep;