Loop through each word in a sentence and capitalize the first letter of each

Almost there with this exercise. I need to convert a given string into the new format

Here Is My Handle Here Is My Spout
.

My code successfully returns

Here Is My Handle Here Is My Spout
. However, when I attempt to
console.log(result.split(" "))
, it shows an extra empty string in the array:
[ '', 'Here', 'Is', 'My', 'Handle', 'Here', 'Is', 'My', 'Spout' ] 
.

I'm struggling to remove the empty string at index 0 and suspect that my function is returning an array of words rather than a single string.

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
    let firstCap = word.replace(word[0], word[0].toUpperCase());
    result += " " + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

Answer №1

The issue lies within the following line:

result = result + " " + firstCap;

If result is empty (""), a space should not be added but rather an empty string like this:

result = result + (result.length ? " " : "") + firstCap;

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
    let firstCap = word.replace(word[0], word[0].toUpperCase());
    result = result + (result.length ? " " : "") + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

A more effective solution would involve using Array#map() followed by Array#join().

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  return words.map(word => word.replace(word[0], word[0].toUpperCase())).join(" ");
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions for creating a directional route on a map using highcharts

I am currently working on implementing highcharts maps with flight routes, similar to the visualization shown in this Highchart-maps with flight routes example. My goal is to display the routes in a way that resembles the output illustrated in this expecte ...

Utilizing datetime looping within MySQL stored procedures

Currently utilizing a mysql stored procedure, I am seeking guidance on creating a loop that updates the variable "starthour" every hour and returns the total output of a query. The loop should continue until the "starthour" reaches November. Below is my c ...

- Deciding When to Utilize Qt Qml Javascript

Trying to understand the relationship between Qt and QML is causing some confusion for me. I'm not sure where C++ should be used versus JavaScript. For instance, when working with QML objects like forms, inputs, and dropdowns, there is inevitably som ...

Stop the repetition of event handlers by utilizing the .off() method to remove duplicates

Here's a scenario where I've assigned two event handlers: $('#myElement').on('click', '.classA', doSomething); $('#myElement').on('click', '.classB', doSomethingElse); Now, the task at ...

How to replicate the pointing direction of an object in Three Js

For my current school project, I am developing a 3D space fighter game. However, I am facing an issue when trying to spawn a projectile based on the direction of my ship's front face. I have managed to find a solution using vectors to spawn projectil ...

Uploading an image along with additional information to Strapi using React

Can you assist me with allowing users to post data on Strapi, such as their name, URL, description, and image? I attempted to add an input type file but encountered a 500 error. I suspect this could be due to the need to call localhost:1337/upload, but I& ...

What might be causing the 500 internal error in jquery.min?

Hello, I am encountering a 500 internal server error when I click this button that performs the following action: $(".btn-email").on('click', function() { swal('Waiting','Please wait, sending email now','info'); ...

html retrieve newly updated page from the provided link

I am facing an issue where I set a cookie on one page and try to unset it on the next page that I reach via a link. However, the cookie only gets unset when I refresh the second page by pressing F5. To test this scenario, I have added a link and some cook ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Exploring the intricacies of Implementing Chromecast Networks, with a curious nod towards potentially mirroring it with

In my current project, I am aiming to replicate the functionality of a Chromecast on a Roku device. To achieve this, I need to first discover the Roku using UDP and then send an HTTP POST request to control it. During a recent developer fest where I learn ...

Every time a new modal is opened, the Bootstrap modal within the code seems to magically multiply itself

Hey there! I recently implemented a room password validation feature for the chat application I developed. To display the password input to users, I utilized Bootstrap's 4 modal. https://i.sstatic.net/4wJQp.png The modal is triggered using jQuery wi ...

Is there a way to calculate the number of days between two dates that are stored in an array

I need assistance with extracting individual days from an array containing start and end dates. My goal is to store the days between the given dates in a new array. Array ( [0] => Array ( [start] => 2019-02-16 [end] => 2019-02 ...

Unable to download file from Express using res.download in Angular

Within my application, I am generating a file on the backend and then attempting to provide it to the user for download via a browser. Despite multiple attempts, I have been unable to achieve this. Below is the code snippet for the express backend: app.g ...

The jQuery click event is failing to trigger

I am facing an issue with some buttons that have specific classes. Here is an example: https://i.sstatic.net/CVIR2.png Each of these buttons contains JSON data stored in a data attribute. I have created a function to detect when a button is clicked and p ...

What is the most effective way to access Firebase Database usage statistics programmatically?

Is it feasible to incorporate a method in my Javascript code to monitor the extent to which I have utilized my Firebase Database quota? ...

What is the reason for NextJS/React showing the message "You probably didn't export your component from the file where it was declared"?

What's the Issue The error code I am encountering Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the ...

JS and its dynamic color changes

A game has been developed using JavaScript and HTML. The game features a table with cells that are assigned IDs for toggling colors using an onClick function. The objective is simple: when a cell is clicked, all neighboring cells, including the clicked one ...

Determine if localStorage is set using jQuery

There is a text on the page inside a div with the id clicker. When this div is clicked, the localStorage value should toggle between 1 and 0. I have provided an example in this JSFiddle link. Although it seems to be working by toggling the value, there ar ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...

Incorporate an image into your webpage with the Fetch API by specifying the image link - JavaScript

I've been attempting to retrieve an image using the imageLink provided by the backend server. fetchImage(imageLink) { let result; const url = `https://company.com/internal/document/download?ID=${imageLink}`; const proxyurl = 'https:/ ...