Using replace()
function in JavaScript has many use cases such as removing unwanted or escape characters in a string. Also, education and languages apps benefit from this feature when auto-correcting multiple words in a paragraph. For example, let’s look at the sentence below:
Helo worLd! Im so glads to be alife in a beautiful worLd.
As you can see, there are a few spelling mistakes that we’d like to correct by replacing certain words with the proper ones.
In this article, we’ll go through two different approaches to solving this problem with minimal code.
replace vs replaceAll
Both functions are very common in JavaScript for replacing strings and characters. The main difference is that replace()
replaces the first occurrence while replaceAll()
replaces all occurrences of the search. For example:
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really?"
However, we can still replace all occurrences using replace()
function along with a regular expression as follows:
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace(/dog/g, 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really?"
Solution 1: Using a loop with a replaceAll function
In this solution, we’ll simply loop through the words that need to be corrected then trigger replaceAll()
.
First, let’s create a dictionary with all the required corrections:
const correction = {
"Helo": "Hello",
"worLd": "world",
"glads": "glad",
"alife": "alive",
"Im": "I'm"
};
Then, we can loop through the keys and replace all occurrences with the proper value:
let str = "Helo worLd! Im so glads to be alife in a beautiful worLd.";
Object.keys(correction).forEach((key) => {
str = str.replaceAll(key, correction[key]);
});
console.log(str);
// expected output: "Hello world! I'm so glad to be alive in a beautiful world."
Solution 2: Using regex with a replace function
Instead of looping through all keys, we can create a regular expression to replace all the words we need. For example, the code below uses regex that can replace all occurrences of “worLd” and “Helo” with “word”:
let str = "Helo worLd! Im so glads to be alife in a beautiful worLd.";
str = str.replace(/worLd|Helo/g, 'world');
console.log(str);
// expected output: "world world! Im so glad to be alife in a beautiful world."
But instead of replacing everything with the same word, we have to find the proper value from the correction
dictionary we created earlier. replace()
provides the option to pass a function instead of a string as a call back for every match. This way, we can use the current matched word to return the required value:
const correction = {
"Helo": "Hello",
"worLd": "world",
"glads": "glad",
"alife": "alive",
"Im": "I'm"
};
let str = "Helo worLd! Im so glads to be alife in a beautiful worLd.";
str = str.replace(/Helo|world|glads|alife|Im/g, matched => correction[matched]);
console.log(str);
// expected output: "Hello world! I'm so glad to be alive in a beautiful world."
We can further improve this by creating a list of words dynamically from the correction
object as follows:
const reg = new RegExp(Object.keys(correction).join("|"), "g");
str = str.replace(reg, (matched) => correction[matched]);
Finally, let’s put everything together in a reusable function and call it autoCorrect()
:
function autoCorrect(text, correction) {
const reg = new RegExp(Object.keys(correction).join("|"), "g");
return text.replace(reg, (matched) => correction[matched]);
}
// Consume the function as follows
let str = "Helo worLd! Im so glads to be alife in a beautiful worLd.";
const correction = {
Helo: "Hello",
worLd: "world",
glads: "glad",
alife: "alive",
Im: "I'm"
};
const correctedText = autoCorrect(str, correction);
console.log(correctedText);
// expected output: "Hello world! I'm so glad to be alive in a beautiful world."
Take a way
The first solution seems to be sufficient enough for a simple word match, but the second can handle more complex match patterns with less code because of the regular expression advantage.
Bye for now 👋