The .replace(/w+/g), function)
works well when replacing one single word inside standardizeMap
, however, it fails when it comes to multiple words.
Sample input (Case 1):
const standardizeMap = new Map([
["Hello world", "How are you"],
["apple pen", "appleP"],
["Swaziland", "Eswatini"])
"Hello world I have an apple pen in Swaziland".replace(/w+/g, (word) =>
standardizeMap.get(word) ? standardizeMap.get(word) : word
)
Output:
Hello world I have an apple pen in Eswatini
Expected output:
How are you I have an appleP in Eswatini
Sample input (Case 2):
"Hello world I have an apple penin Swaziland".replace(/w+/g, (word) =>
standardizeMap.get(word) ? standardizeMap.get(word) : word
)
Expected output:
How are you I have an apple penin Eswatini
How can I achieve it?
2
Answers
You need to iterate over each key value in
standardizeMap
and replace all occurrences of the key.Calling
String.replace(/w+/g, (word) => doStuff())
(or replaceAll, same thing except that replaceAll requires the ‘g’ flag) will let the method perform the replacement for each matching sequences ofw+
. You can see them using the console logging:So, you should loop over your map and for each entry, replace in the text all occurrences of its key to its value.
Instead, you should loop through your map and, for each entry, replace in the text all occurrences of the entry’s key with its value, as shown below for example.