Code Smell 247 – Javascript Replace

You want to replace all, but you replace one ocurrence

TL;DR: Bad function names will lead you to defects

  1. Avoid ambiguous or bad names

  2. Wrap with your functions

  3. Use mature languajes

Some names in immature languages break the bijection principle.

When you use them, you agree on some semantics that are not the actual behavior.

Consequently, you must know accidental implementations to avoid this defect.

Wrong

const pets = '😺🐶😺';
const justDogs = pets.replace('😺', '🐩'); const catsArePresent = justDogs.includes('😺');
// returns true
Enter fullscreen mode
Exit fullscreen mode

Right

const pets = '😺🐶😺'; const justDogs = pets.replaceAll('😺', '🐩');
// Or
const justDogs = pets.replace(/😺/g, ''); const catsArePresent = justDogs.includes('😺');
// returns false
Enter fullscreen mode
Exit fullscreen mode

[X] Automatic

You can search and forbid the usage of replace() in your code and define replaceFirst() if you need to change only the first occurrence

[x] Beginner

All generators avoided this problem.

ChatGPT and Copilot use Regular Expressions to solve the problem.

Gemini and Claude failed to spot the mistake.

None of them use replaceAll() (introduced in ES2021)

Using replace() instead of replaceAll() would not fully achieve the intended result of replacing all occurrences.

It would only replace the first occurrence, potentially leading to incorrect behavior if there are multiple occurrences.

Code Smells are my opinion.

Photo by Jari Hytönen on Unsplash


We must not blame programmers for their bugs. They belong to them only until the code is merged to the repository. After that, all bugs are ours!

Yegor Bugayenko


This article is part of the CodeSmell Series.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Digital marketing invogue nexus web design. Study your competitors’ websites and social media channels.