Converting a Javascript string to 'Title Case' does not yield any results

I'm having trouble identifying the bug in this code as it's not generating any output:

function convertToTitleCase (inputString) {
        var wordArray = inputString.split(' ');
        var outputArray = [];

        for (var j = 0; j < wordArray.length; j++) {

            outputArray.push(wordArray[j].charAt(0).toUpperCase() + wordArray[j].slice(1));
        };

        return outputArray.join(' ');
    }

    alert(convertToTitleCase("the quick brown fox"));

Answer №1

In my opinion, changing arr[x] to arr[i] would be more appropriate.

function reverseWords(str) {
        var arr = str.split(' ');
        var reversed = [];

        for (var i = 0; i < arr.length; i++) {

            reversed.push(arr[i].split('').reverse().join(''));
        };

        return reversed.join(' ');
    }

    alert(reverseWords("hello world"));

Answer №2

Concise solution in a single line:

let sentence = "the quick brown fox",
    capitalizedWords = sentence.split(" ").map(w => w[0].toUpperCase() + w.slice(1)).join(" ");

console.log(capitalizedWords);   // "The Quick Brown Fox"

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

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

Mocha: A Unique Perspective on Testing the express.Router Instance

As I was developing a JavaScript controller file, I came across the need to test if my controller instance contains an instance of the express method called Router(). import {assert} from 'chai'; import {UF_Controller} from '../../controlle ...

Error encountered: API key is required - Issue found in: /node_modules/cloudinary/lib/utils.js at line 982

I encountered an issue with cloudinary while trying to upload photos on my website after adding a new function for Facebook login. "/home/ubuntu/workspace/YelpCamp/node_modules/cloudinary/lib/utils.js:982 throw "Must supply api_key"; ^ Mus ...

Angular is unable to detect the dynamically loaded page when using Extjs

Within my Extjs SPA system, I have integrated Angular along with the necessary modules to be used on a page that is being referred in an external HTML panel in Extjs. While Angular is defined and functioning properly everywhere else, it seems to not work ...

Is there a way to implement a targeted hover effect in Vue Js?

I'd like to create a hover button that only affects the nested elements inside it. Right now, when I hover over one button, all the nested elements inside its sibling buttons get styled. Any ideas on how to fix this? <div id="app"> <butto ...

"Transmitting a message with socket.io upon establishing connection

Currently getting the hang of socket.io and giving it a try. I have a straightforward app where clicking the display button shows an image on the screen in real time. I have a couple of questions. Firstly, my main concern is regarding the synchronization ...

I'm baffled as to why this code isn't functioning properly

My current script seems to be malfunctioning for some reason. I'm using a combination of express, socket.io, jade, and node.js in this setup. Below is the script I am working with: var socket = io.connect(); function addMessage(msg) { var currentDa ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

What could be causing my AngularJs routing and animation to bypass the second redirection?

Recently started working with Angular and experimenting with routing and animations to manage my page transitions. I followed a helpful guide that helped me set everything up. I encountered a few issues: When trying to link back to the landing page (home ...

Employ the v-model directive in conjunction with a checkbox in scenarios where v-for is implemented with the properties of an object

When utilizing v-model with a checkbox in conjunction with an array of objects, it functions correctly: new Vue({ el: '#example', data: { names: [ { name: 'jack', checked: true }, { name: 'john', checked ...

Trouble with toggling div visibility using jQuery and AJAX

I'm trying to display a specific div based on the result of an SQL query. The problem I'm facing is that I can't seem to toggle the divs asynchronously. Currently, the page needs to be reloaded for the div to reflect the changes. <?ph ...

Finding the Key in a Multidimensional Array using PHP

I am currently working with the following array structure: Array ( [carx] => Array ( [no] => 63 ) [cary] => Array ( [no] => 64 ) ) I am trying to figure out how to find t ...

Node.js removes leading zeroes from dates

I am looking to generate a string with the current date and time in the format: "2021-06-02 09:37:38" const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today); ...

Is there a way to conceal an element using identical markup with jquery?

Having trouble with two custom dropdown lists that share the same markup. Ideally, only one should be visible at a time. However, both are currently opening simultaneously. Additionally, I need them to close when clicking outside of the list. It's ne ...

"An issue arises where the bokeh plot fails to render when generating a

I have been working on embedding a bokeh plot within a webpage served by a simple Flask app. I am using the embed.autoload_server function that I found in the bokeh embed examples on github. While everything seems to be functioning correctly on the Python ...

Automatically reset the form after submission in CakePHP 1.3

I've encountered an issue with my report form that is linked multiple times on a page to a jQuery dialog box. To prevent cross-posting, I added a random string to the submission process. After successfully submitting the form on a single page access, ...

Deleting items from an array of files and directories with PHP

Currently, I am attempting to retrieve a list of directories within a specified path using the scandir method and then removing any files from the resulting array. However, I am encountering issues with my echo statement. The code snippet I am working on ...

Transmit a fixed-size array to the workforce

I need to distribute an array of size 336 into segments for my 8 workers. I want each worker to receive segments with sizes of 12, 18, 30, 36, 48, 54, 66, and 72. The pattern is to add 6 and then 12 consecutively. So far, I have managed to split the array ...

Combine a string variable and an array object in JavaScript or AngularJS

Hey there! I'm currently attempting to combine an array, a variable, and a "." in between them. The object I receive from json is stored in data, while valuePickup represents a variable. My current approach: self.GetIndex = function (valuePickup) { ...

Passing a variable from the server to the client function in Meteor with a delay

When I invoke a server function from the client side, it executes a UNIX command and retrieves the output on the server. However, I face an issue where the result is immediately returned as undefined by Meteor.call because the exec command takes some time ...