Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 359
patrick.altair Avatar asked Sep 19 '14 16:09

patrick.altair


People also ask

How can I replace all characters in a string using jQuery?

The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements. Parameters: This method accepts two parameter as mentioned above and described below: content: It is the required parameter which is used to specify the content to insert.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do you replace an element with another in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.


1 Answers

Have your replace use a regex with a global replace.

Change:

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

to:

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

codepen example

like image 116
j08691 Avatar answered Oct 04 '22 03:10

j08691