Simple jQuery code snippet to replace all occurrences of characters (or strings) within a string. It could be used to find and replace all substrings found inside a string. Don’t forget to leave out the quotes on the first parameter (the g stands for global, you can also use i for an case insensitive search).

//global search in string
str = str.replace(/find/g,”replace”);
//OR global and case insensitive search in string
str = str.replace(/find/gi,”replace”);

global replace with dynamic var

//global replace
var regex = new RegExp('{'+fieldname+'}', "igm");
$itemForm = $itemForm.replace(regex, fieldvalue);

Also see: jQuery Read Text File Via AJAX.


Tags: jquery global replace, jquery insert string inside string, jquery replace all
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Deepti

    iam not able to use.. this wht will be in
    str = str.replace(/find/gi,”replace”);

    if i want to replace a particular word in string..
    like thee is sentence
    i want to make this happen, it happen that way only
    i want to replace happen word with some other word..
    is this right.. but its not working..

    • Name

      Check your quotes.

      Try single quotes for example:


      • HongHieu

        if i do:
        var str = “happen”;

        it do not work.
        help me

  • SatheeshKumar

    Really this was useful. Non of my search told me to remove the quotes in the first parameter. Thanks a Lot.

  • Sam

    This is Javascript not jQuery.


    Works like a charm, thanks

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.