1. Use Fail-Safe
Using more replace() in chain than expected occurrences, this will not harm in anyway but it is not a good practice if because no. of occurrence is not predictable.
var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";
StrToRepalce = StrToRepalce.replace('Scala', 'F#')
.replace('Scala', 'F#')
.replace('Scala', 'F#')
.replace('Scala', 'F#');
console.log(StrToRepalce);
2. split() join() combinationThis approach will work for any number of occurrences, but more performance costly.
var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";
StrToRepalce = StrToRepalce.split("Scala").join("F#");
console.log(StrToRepalce);
3. Using Regular ExpressionVery short and simple regex will work for any no. of occurrences, but error prone for special characters.
var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";
StrToRepalce = StrToRepalce.replace(/Scala/g, 'F#');
console.log(StrToRepalce);4. RegEx with Special Character handlingSame as previous approach but will handle special characters too.
var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";
StrToRepalce = StrToRepalce.replace(new RegExp("Scala".replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), "F#");
console.log(StrToRepalce);
5. Adding replaceAll() to string prototype to use globallyAbove approach is all good, but it is better to place this function to string prototype so can be can from any where across application.
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
var StrToRepalce ="Scala is a Functional Programming Language. Scala is easy to learn.";
StrToRepalce = StrToRepalce.replaceAll("Scala", "F#");
console.log(StrToRepalce);
