How to Find text and replace using jQuery

前端 未结 3 1567
迷失自我
迷失自我 2020-12-30 16:49

Im trying to find a solution to search for a text string \"Tony\" contained in the DOM and replace it with a text String \"Tiger\".

Anyone have any insight or ideas

相关标签:
3条回答
  • 2020-12-30 17:02

    You can use this to search all children of the body element and replace the text...

    $('body').children().each(function(){$(this).text( $(this).text().replace('Tony','Tiger') )});
    

    It uses jQuery. It also should only alter the textual content of elements and none of the HTML formatting...

    You can also use this method which uses a RegExp and will get all nested elements:

     $('body').html( $('body').html().replace(/Tony/gi,'tiger') );
    
    0 讨论(0)
  • 2020-12-30 17:03

    Is it possible to couple this with a server-side solution? You could wrap every occurence of the word server side with a special class, like <span class="replaceme">texttoreplace</span>.

    Running a javascript replace on the resulting classes only should speed things up.

    0 讨论(0)
  • 2020-12-30 17:25

    Page wide, you can use something like this:

    var $body = $('body');
    var html = $body.html();
    var newHtml = html.replace('Tony', 'Tiger');
    $body.html(newHtml);
    

    Or, if you have a more specific container, use jQuery to select that child container and do the same thing.

    Either way, it is sort of a shotgun approach. It will change the string in both visible text and html element attributes. A more detailed approach might be needed if the string needed to be ignored in certain locations.

    0 讨论(0)
提交回复
热议问题