Photo by Andrew Ridley on Unsplash
2 min read
replace but there is a small gotcha that can lead to subtle bugs that at first can be confusing.
Typical usage of string replace for example to remove all spaces:
let s = 'nice weather today'; s.replace(' ', ''); console.assert(s === 'niceweathertoday', 'niceweathertoday');
The assertion above fails. This can be confusing since the expectation is that the spaces will be removed. If we console log the value of
s at the end of the code sample we get
nice weather today. This leads to our first gotcha:
All string methods return a new string!
In our code sample replacing
s.replace(' ', ''); with
s = s.replace(' ', ''); is correct since
replace will return a new string.
But the assertion still fails!!
This leads us to our next gotcha:
If the pattern is a string, only the first occurrence will be replaced.
If we provide a string as the pattern like in our case an empty string then only the first occurrence gets replaced i.e
To resolve this we need to provide a Regex pattern as our pattern. In our case, we should do
Our assertion still fails!!
This leads us to our third gotcha.
Use Regex global flag to match all cases in the string
In the case above, again only the first occurrence of the space character gets replaced.
To fix we need to use the global flag
s.replace(/\s+/g, '');. This tells the regex engine to test all possible matches in the string.
The three key takeaways are:
- All string methods return a new string!
- If the pattern is a string, only the first occurrence will be replaced. Use Regex pattern if you want to replace multiple occurrences of a character in the string.
- Use the Regex global flag to match all cases in the string.