Leonard Kioi Kinyanjui
Learn & Build

Learn & Build

Javascript String Replace Gotchas

Photo by Andrew Ridley on Unsplash

Javascript String Replace Gotchas

Leonard Kioi Kinyanjui's photo
Leonard Kioi Kinyanjui
·Apr 28, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

To replace a character from a string with another in JavaScript, the goto method is 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 s.replace returns 'niceweather today'.

To resolve this we need to provide a Regex pattern as our pattern. In our case, we should do s.replace(/\s+/, '');.

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.
 
Share this