How to replace in html string only in texts within (between) tags?

Asked

Viewed 2,928 times

4

I created a search that marks the text that was found.

  • OBS 1: The search is done in a string that is HTML.
  • OBS 2: I check if there is text inside this HTML through the index.
  • OBS 3: If you find one replace in all occurrences of the text, replacing the text with the text itself only within a div that marks with css (Example: '<div class='marcado'>texto</div>' instead of just 'text').

The problem I realized later is that if I search the word html or body, or href, etc, I end up breaking the html of the page after it does the replace, because I’m playing with tags and html attributes inside my string.

So I’d like to get around this by replacing only texts that are within these tags. But I still can’t imagine in my head any way of doing that. I need help with solutions ideas for this, even if it’s not the explicit one in the question.

  • You can use the innerText instead of innerHTML. If not, I believe you’ll have to do an in-depth search.

  • The problem is that the innerText, depending on the context in which it is searching, it will turn the tags into text only.

3 answers

3


If you want to search for a specific word and replace it, without influencing tag declarations, either in name or in attributes, you can use the following example, with jQuery.

 $(function(){
            
     var filterWord = function(){
         var self = $(this),
             text = self.html();
         
         if (self.children().size()) {
             self.each(filterWord);
         } else {
           self.html(text.replace(/a|p|h1|texto/gi, 'p'))
         }
         
     };
     
     $('.container').find('*').each(filterWord);
     
     filterWord.call($('.container'));
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
    <h1>texto</h1>
    <p>texto que está na tag</p>
    
    texto
    <a class="texto" href="#">Meu texto</a>
</div>

updating

I added the check to apply a recursion. With the method children i check if inside the current element has a tag. If it exists, it applies the recursion on the child element of self. If not, it replaces the text, certain that there are no tags to be replaced, and yes, only content.

See it working on JSFIDDLE

  • In your fiddle, when I try to replace 'H1' by 'p' it replaced. The intention is that it does not, just do in the contents inside H1

  • I will update the solution

  • @Joaopaulo, updated answer. No substitute now h1 for p. Can test the will :)

3

If you want to replace only the content of the tags, you can do so

var html = $.parseHTML('<b> ola mundo</b>\
<a href="hehehe"> vem mundo </a>\
<div> nao troque o mundo </div>\
<span> mundo nao mundo meu mundo </span>');

 var troca = ["mundo", "troll"];


 for (var tag in html) {
   $(html[tag]).text($(html[tag]).text().replace(new RegExp(troca[0], "g"), troca[1]));
 }


 for (var tag in html) {
   document.write($(html[tag]).text() + "<br>");
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you want to do this for all page elements, just use html = $("*")

if you are working on the DOM itself, you can use this function

function htmlReplace(html, stringA, stringB) {
    for ( var tag in html) {
    $(html[tag]).text($(html[tag]).text().replace(new RegExp(stringA, "g"),stringB));
    }    
}

3

You can do an in-depth search and check the Node type:

var content = document.getElementById("content");
var txtFind = document.getElementById("txtFind");
var txtReplace = document.getElementById("txtReplace");
var btReplace = document.getElementById("btReplace");

var replaceText = function (elem, find, replace) {
    for (var indice in elem.childNodes) {
        var childNode = elem.childNodes[indice];
        if (childNode.nodeType == 3) {
            childNode.data = childNode.data.replace(find, replace);
        }

        if (childNode.nodeType == 1) {
            replaceText(childNode, find, replace);
        }
    }
}

btReplace.onclick = function () {
    var find = new RegExp(txtFind.value, 'g');
    var replace = txtReplace.value;

    replaceText(content, find, replace);
}
<div id="form">
    <div>
        <label for="txtFind" >Find:</label>
        <input id="txtFind" type="text" />
    </div>
    <div>
        <label for="txtReplace" >Replace:</label>
        <input id="txtReplace" type="text" />
    </div>
    <div>
        <input id="btReplace" type="button" value="Substituir" />
    </div>
<div>
<div id="content">
    Teste - Lorem Ipsum
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce molestie urna dignissim justo iaculis aliquam. Ut auctor sit amet justo laoreet semper. Curabitur hendrerit ornare vulputate. In dictum dui et sem ultricies, id rhoncus nisi dignissim. Suspendisse ac enim sollicitudin, gravida leo eu, fringilla nisl. Suspendisse potenti. Aenean blandit ut purus eget varius. Fusce ornare pretium mauris, placerat viverra est facilisis in. Nunc elementum, leo ac tincidunt luctus, ipsum ipsum laoreet tortor, finibus pulvinar enim erat sit amet mi. Phasellus vulputate fringilla tortor, id tempus urna suscipit id. Vivamus ipsum libero, lacinia quis felis mollis, luctus viverra mi. Praesent id elementum metus, quis porttitor est. Integer condimentum rhoncus eros eget varius. Vestibulum vitae arcu libero.</p>
    <p>Suspendisse ultrices neque ornare convallis posuere. Curabitur consectetur libero ut urna sodales, eget vehicula magna sodales. Sed a tincidunt lacus, non varius odio. Morbi mollis hendrerit mollis. Duis mauris libero, semper eu lectus ut, porta accumsan diam. Sed tristique tortor est, non luctus nulla cursus quis. Proin lacinia, leo vel mattis efficitur, turpis nulla finibus nulla, vel consectetur erat dui ut turpis. Curabitur sagittis elementum ante a rhoncus. In in lorem et turpis condimentum rutrum et at metus. Proin vitae tellus elementum, feugiat nulla ac, porta sapien. Donec dapibus nulla sit amet urna porta consectetur. Donec tristique massa justo, vel finibus turpis aliquam et. Ut nisl elit, fermentum et ultrices sit amet, rutrum a est. Proin vel varius neque. Integer bibendum porta neque, at vulputate ante bibendum vel.</p>
    <p>Sed laoreet nisl in nisl tempor, vitae bibendum arcu porta. Vivamus feugiat felis euismod magna tincidunt, non cursus nunc ultrices. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras ac mi eu urna molestie vehicula vitae a quam. Morbi et eros nec libero auctor imperdiet. Nunc pharetra sapien sem, in molestie tellus pellentesque eu. Mauris sit amet ante placerat diam pulvinar tempus. Morbi mollis imperdiet tortor. Pellentesque mollis leo non tellus congue, non molestie quam condimentum. Mauris malesuada, felis nec faucibus faucibus, purus ante faucibus nulla, et hendrerit nisl tortor a turpis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque tempus eros ut massa iaculis euismod. Morbi vestibulum enim nisl. Sed volutpat tristique consectetur.</p>
    <p>Proin non commodo leo, non ornare mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nam egestas est non malesuada iaculis. Ut congue laoreet vehicula. Nunc velit enim, sollicitudin quis orci tristique, lacinia lacinia augue. Nam at mattis purus, eget pulvinar odio. Duis et dapibus eros. Praesent rhoncus vitae turpis non tempus. Sed semper sit amet ipsum ac interdum. Nunc pulvnisi, vitae aliquam est feugiat eu. Pellentesque scelerisque nisl et molestie malesuada. Maecenas ullamcorper sapien quis enim dictum, sed pellentesque risus consequat.</p>
    <p>Donec porta turpis at est rutrum, sed interdum dui semper. Donec lectus ligula, egestas ut sagittis non, mattis eu dolor. Cras convallis sem non urna tristique, ac sagittis magna egestas. Maecenas imperdiet, nulla at mattis sodales, neque nibh ullamcorper enim, at sollicitudin eros sem at diam. Sed dui magna, pretium a lobortis id, accumsan ac nibh. Ut neque quam, elementum in fringilla elementum, scelerisque vel est. Etiam blandit, dolor eu suscipit pharetra, massa tellus facilisis sem, nec elementum eros est ac libero. Nam faucibus mattis ex, ac lacinia metus finibus eget. Cras sit amet turpis rutrum, volutpat tortor non, cursus nibh. Vestibulum congue justo nec elit fermentum, mattis sodales sem convallis.</p>    
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.