JavaScript code for replacing using the regular expression:
function replaceWithRegex(){
var replaced = str.replace(/abc/g, "JavaScript");
alert(replaced);
}
Regular express is used for performing case sensitive replace in a string.
var dog = "I love dog. Dog is faithful animal.";
function replaceWithRegexCaseSensitive(){
var replaced = dog.replace(/dog/g, "cat");
alert(replaced);
}
Regular express is used for performing case in-sensitive replace in a string.
var str2 = "I love dog. Dog found in abundant around the world.";
function replaceWithRegexCaseInSensitive(){
var searchString = "dog";
var regEx = new RegExp(searchString, "ig");
var replacementString = "cat";
var replaced = str2.replace(regEx, replacementString);
alert(replaced);
}
In JavaScript split() and join() functions can be used for replacting all string.
var dog = "I love dog. Dog is faithful animal.";
function replaceWithSplitAndJoin(){
var splitted = dog.split("dog");
var replaced = splitted.join("cat");
alert(replaced);
}