Using a JavaScript array to capitalize every word in a sentence

I'm working on a homework assignment that requires me to create a function that capitalizes each word in a sentence passed into it. My initial idea was to split the sentence into an array, loop through each word, capitalize the first letter of each word, and then join the words back together into a new string. Here is the code I have so far:

function titleCase(string) {
  var words = string.split(' ');
  for (var i = 0; i < words.length; i++) {
    const lettersUp = ((words[i])[0]).toUpperCase();
    const result = words[i].replace((words[i])[0], lettersUp);
    return result;
  }
}

The issue I am facing now is that the code only returns the first word of the input sentence. I suspect there might be an error in my loop logic, but I can't seem to pinpoint where the problem lies. Any assistance or guidance would be much appreciated. Thank you.

Answer №1

It seems like your code is not functioning properly after the first loop iteration.

A possible solution could be the following approach:

function capitalizeFirstLetterOfEachWord(sentence) {
    var wordsArray = sentence.split(" ");
    for (var j = 0; j < wordsArray.length; j++) {
        const initialChar = ((wordsArray[j])[0]).toUpperCase();
        wordsArray[j] = wordsArray[j].replace((wordsArray[j])[0], initialChar);
    }
    return wordsArray.join(" ");
}

Consider using regular expressions for an even more efficient solution. Give it a try!

Answer №2

Make sure to keep everything straightforward and uncomplicated - there's no necessity for additional variables like lettersUp, simply adjust the strings within the words array.

function modifyCase(str) {
  var words = str.split(' ');
  for (var i = 0; i < words.length; i++) {
    words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);     
  }
  return words.join(' '); 
}

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

Error in TypeScript detected for an undefined value that was previously verified

I have developed a function that can add an item to an array or update an item at a specific index if provided. Utilizing TypeScript, I have encountered a peculiar behavior that is puzzling me. Here is the Playground Link. This simple TypeScript functio ...

Launching the ngx Modal following an Angular HTTP request

Trying to trigger the opening of a modal window from an Angular application after making an HTTP call can be tricky. Below is the content of app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/pla ...

Can Sync blocking IO be implemented solely in JavaScript (Node.js) without the use of C code?

Is JavaScript intentionally designed to discourage or disallow synchronous blocking I/O? What is the reason for the absence of a sleep API in JavaScript? Does it relate to the previous point? Can browsers support more than one thread executing JavaScript? ...

Python dialog pop-up application

Looking for some assistance.. I'm aiming to create a Python program utilizing tkinter to display a message box. After closing the initial message box, I'd like two more boxes to appear. Subsequently, upon closing those two boxes, four more shoul ...

Undefined is returned after resolving - React - JavaScript API

Learning React and JavaScript is a bit challenging for me, especially when it comes to understanding how Promises and resolving work. I'm currently working on an API to log into an application with an internal SQL database. The queries are functionin ...

Finding a way to retrieve WFS at a later time using GeoExt can be

Could you assist me with setting up WFS on GEOExt? I have gone through a tutorial and found this code snippet. proxy: new GeoExt.data.ProtocolProxy({ protocol: new OpenLayers.Protocol.WFS({ url: "/geoserver/ows", version: "1.1.0", ...

Every operation pertains to the initial element

<textarea id="bbcode_enabled"></textarea> <textarea id="bbcode_enabled"></textarea> <textarea id="bbcode_enabled"></textarea> $(document).ready(function() { $("#bbcode_enabled").each(function () { $(this).b ...

Efficient - Managing numerous database connections

I am currently working on a project using node.js and I have created a login form where users need to select the database they want to connect to. However, I am uncertain about how to establish a connection with the selected database. Is there a way for m ...

C Sharp: Receiving data of indeterminate size using a UDP socket

Currently, I am utilizing a UDP socket for sending and receiving objects. The process involves serializing the objects into a byte array, sending them, and then receiving them with a client. However, before I can receive the objects, I need to allocate a b ...

Discover elements within an array that belong to the given set in Python

As someone who is new to Python with a background in MATLAB, my explanation of the problem may be a bit unclear. In MATLAB, when dealing with 1000 arrays of size 15x15, we typically define a cell or a 3D matrix where each element is a matrix of size (15x15 ...

Axis incorporating additional padding for extensive domains

Encountering a peculiar issue with d3 axis generation. When creating a bottom x axis using d3.axisBottom() for ordinal domain values, extra padding is being added at the starting and ending points of ticks on the axis. This happens when the d3.scaleBand() ...

Contrast the values extracted from an array of objects with a string in React Native/Javascript

I am attempting to implement an If statement to compare a property from an object in an array with a String. I have set up a for-loop, but for some reason, the conditional statement does not seem to be triggering. Below is the code snippet I am using to sa ...

Enhanced jQuery Pop-Up Panel

A few issues to address: 1) My goal is to optimize the efficiency of this script. 2) When a user clicks on either pop-out button, it opens a window and hides the element. (Currently using .detach() to remove the embedded video player because in Firefox . ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

Tips for successfully sending an API request using tRPC and NextJS without encountering an error related to invalid hook calls

I am encountering an issue while attempting to send user input data to my tRPC API. Every time I try to send my query, I receive an error stating that React Hooks can only be used inside a function component. It seems that I cannot call tRPC's useQuer ...

Switching the parameter to navigate to the appropriate page

Hi there, I'm looking to implement a quick change using the onchange parameter. Can someone assist me in using the onchange parameter to navigate to a new page? So, if someone selects for instance Basic info, they will be directed to a new page custo ...

jQuery encounters a 400 error while attempting to make a GET request

I have been using a jQuery ajax GET request that sends a clientId to the server. If the clientId is invalid, the server returns a 400 "Bad token etc..." error message. While this setup works fine, I am puzzled by why jQuery displays this error in the conso ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

I can't seem to figure out why I continue to receive the error message stating that 'app.get is not a function'

Below is the code I am currently using: const request = require('request'); const app = require('express'); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); Unfortunately, I keep e ...

Verify if the element's visibility can be confirmed by utilizing the IntersectionObserver function

I am currently working on my next.js component layout and trying to determine when a modal window containing the div #snipcart becomes visible on the screen. I have attempted to utilize the IntersectionObserver for this purpose, but I am not receiving any ...