Replace multiple strings with multiple other strings
To do the string-replace dance with javascript, you can use an object (aka: a "map") for your "replace with what" pairs, and a regular expression (regex) to catch them all.
In this code, we're casting a regex
pokeball to catch all keys from our map
. Then, replace()
craftily uses the caught match to return our corresponding string replacement.
Dance with dynamic replacements
What happens if we have a flashmob of words that keep changing and want to join our replace party? Fear not. Let's choreograph a reusable function to keep the dancefloor open:
Don't lose your words
The devil's in the detail and we don't want to replace parts of words like a clumsy DIYer. That's why we use word boundaries \b
in our regex to ensure precision:
Our regex
is now like a well-trained dog, fetching only whole words that match keys in our map
.
Safe replacement
In the real world, we don't always find what we're looking for. So we need our function to handle those "oopsie-daisy" situations when the replacement isn't needed:
With || match
, we ensure if a match isn't in our map, the original word sticks around like the loyal friend it is.
Go the extra mile with polyfill
Sometimes, we need to turn back the clock, and for those situations include a polyfill. This way, we're friendly with the older browsers:
This polyfill brings replaceAll
back to the future!
The placeholder trick
Sometimes, string replacement feels like solving a Rubik's cube, with overlapping replacements causing chaos. The solution? Use placeholders:
This placeholder strategy might seem like a magic trick, but it's simple: First, replace old strings with placeholders, then swap the placeholders with the new strings. Abracadabra!
Using modern syntax
Our modern JavaScript syntax can make our code enlighten:
-
Arrow functions for short and sweet callbacks:
-
Use template literals to make regex more readable:
-
Leverage destructuring and spread operator to keep everything neat and tidy:
Wrapping it up
Your grandma might not understand what 'performance optimization' means but she definitely knows the value of readability. So let's keep that in mind:
- Consider performance when handling large pieces or numerous replacements.
- Resort to concise and efficient regular expressions, to avoid unleashing the dark forces within your code.
Was this article helpful?