replaceAll() In JavaScript Without jQuery

When we use replace() in any string, most of the time it is not easy to predict how many occurrences we will have to replace. There can be many approaches to do it. Let's have a look at all o them and proceed to the best one.
  1. Use Fail-Safe
     
    Using more replace() in the chain than expected occurrences, this will not harm in any way but it is not a good practice because no. of occurrence is not predictable.
    1. var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";  
    2.   
    3. StrToRepalce = StrToRepalce.replace('Scala''F#')  
    4. .replace('Scala''F#')  
    5. .replace('Scala''F#')  
    6. .replace('Scala''F#');  
    7. console.log(StrToRepalce);  
  2. split() join() combination
     
    This approach will work for any number of occurrences, but it is more performance costly.
    1. var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";  
    2. StrToRepalce = StrToRepalce.split("Scala").join("F#");  
    3. console.log(StrToRepalce);  
  3. Using Regular Expression
     
    Very short and simple. Regex will work for any no. of occurrences, but it is error-prone for special characters.
    1. var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";  
    2.   
    3. StrToRepalce = StrToRepalce.replace(/Scala/g, 'F#');  
    4.   
    5. console.log(StrToRepalce);  
  4. RegEx with Special Character handling
     
    Same as the previous approach, but it is capable of handling special characters too.
    1. var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";  
    2. StrToRepalce = StrToRepalce.replace(new RegExp("Scala".replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), "F#");  
    3. console.log(StrToRepalce);  
  5. Adding replaceAll() to string prototype to use globally
     
    The above approaches are all good but it is better to place this function to string prototype so it can be run from anywhere across the application.
    1. String.prototype.replaceAll = function (find, replace) {  
    2. var str = this;  
    3. return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);  
    4. };  
    5. var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";  
    6. StrToRepalce = StrToRepalce.replaceAll("Scala""F#");  
    7. console.log(StrToRepalce);