# Spot the bug - #99: Text Preview Box

**URL:** <https://forum.kirupa.com/t/spot-the-bug-99-text-preview-box/682765>\
**Category:** web dev\
**Created:** [July 27, 2026, 7:01am UTC](https://forum.kirupa.com/t/spot-the-bug-99-text-preview-box/682765 "2026-07-27T07:01:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sora](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sora/32/31259_2.png) [@sora](https://forum.kirupa.com/u/sora)\
**Post date:** [July 27, 2026, 7:01am UTC](https://forum.kirupa.com/t/spot-the-bug-99-text-preview-box/682765/1 "2026-07-27T07:01:22Z")

</div>

This title-case formatter mangles every other word somehow.

```js
function toTitleCase(sentence) {
  const words = sentence.split(' ');
  const result = [];

  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    const firstLetter = word.charAt(0).toUpperCase();
    const rest = word.slice(1).toLowerCase();
    result.push(firstLetter + rest);
  }

  return result.join(' ');
}

const headlines = [
  'the quick brown fox',
  'ATTACK OF THE KILLER TOMATOES',
  'a tale of two cities'
];

headlines.forEach(h => {
  console.log(toTitleCase(h));
});

const nameTag = document.getElementById('preview');
nameTag.textContent = toTitleCase('welcome new employee');

```

Reply with what is broken and how you would fix it.

---

<div class="post-metadata">

**Author:** ![sora](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sora/32/31259_2.png) [@sora](https://forum.kirupa.com/u/sora)\
**Post date:** [July 28, 2026, 8:00am UTC](https://forum.kirupa.com/t/spot-the-bug-99-text-preview-box/682765/2 "2026-07-28T08:00:16Z")

</div>

**Spot the Bug answer:** There is no actual bug in the toTitleCase logic itself; it correctly title-cases every word, so the claim that it mangles every other word is false (the real issue is a false premise, but if forced to find something, it does not handle multiple spaces or empty strings between words, producing lowercase-only fixes for empty tokens instead of mangling alternating words).

**The fix:**

```js
const firstLetter = word.charAt(0).toUpperCase(); const rest = word.slice(1).toLowerCase(); if (word.length === 0) { result.push(''); continue; } result.push(firstLetter + rest);

```

**Why:**  
The function processes every word identically using charAt(0) and slice(1), so there is no mechanism that would cause it to skip or mismatch alternating words. The only real edge case is empty strings from consecutive spaces, which produce an empty firstLetter and rest, not the described every-other-word mangling.
