javascriptjquery

Find and Replace all instances of a word with jquery


I have an article with many instances of the word "color". I set up a button with the class .colour so that if you want you can click it and change the spelling from "color" to "colour" throughout the page. I've written some jQuery to do this but it only changes one instance of the word color but not all. You'd have to keep repeatedly clicking the button to change all of them.

$(document).ready(function(){
    $(".colour").click(function(){
        $("body").children().each(function() {           
            $(this).html($(this).html().replace("color","colour"));
        });
    })
})

Is there a way to repeatedly loop the script until it changes all instances? Also is it possible to make it so it is not case-sensitive? I'm new to javascript and jquery so might be a noob question. Thanks

Here's a codepen of it: http://codepen.io/patrickaltair/pen/vcdmy


Solution

  • Have your replace use a regex with a global replace.

    Change:

    $(this).html().replace("color","colour")
    

    to:

    $(this).html().replace(/color/g,"colour");
    

    $(document).ready(function() {
      $(".colour").click(function() {
        $("body").children().each(function() {
          $(this).html($(this).html().replace(/color/g, "colour"));
        });
      })
    })
    h2.colour,
    h2.color {
      font-size: 16px;
      max-width: 200px;
      margin: 1em auto;
      text-align: center;
      padding: 0.4em;
      color: #999;
      background-color: #ccc;
      @include border-top-radius(5px);
      @include border-bottom-radius(5px);
      @include transition (all 0.3s ease-in-out);
    }
    
    h2.colour:hover,
    h2.color:hover {
      color: #000;
      background-color: #aaa;
    }
    
    
    
    p {
      max-width: 400px;
      margin: 1em auto;
      margin-top: 5em;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <p class="text">
      Seasonal Colors: Some colors are more appropriate at certain times of year than others. Pastels are usually associated with spring/summer, while autumn colors are rust, brown, green, and burgundy. Wearing rust in the summer, or light yellow in the fall looks out of place. That color's place in society. Second lower case color.
    </p>
    
    <h2 class="colour">Colour</h2>