What is the best approach for handling the spaces within the code?

Currently tackling a Code Wars challenge where I need to create a string with alternating upper and lowercase letters, starting with an uppercase letter. Here's the link to the challenge.

This is the approach I've taken:

function toWeirdCase(string){
  let newString = [];
    for(let i in string ) {
        if(i%2 == 0) {
            newString.push(string[i].toUpperCase());
        } else {
            newString.push(string[i].toLowerCase());
        }
    }
    return newString.join('');
}

I'm currently facing an issue with accounting for spaces and ensuring that each word starts with a capital letter.

Answer №1

Instead of inefficiently processing character by character, consider splitting the string into words first. This approach reduces the need for unnecessary conditionals as you can focus on each word individually. By starting with uppercase letters every time and then rejoining the words after processing, you create a simpler solution. Here is an example:

function toWeirdCase(string) {
    return string.split(' ')
        .map(word => word.split('')
            .map((c, i) => i % 2 === 0 ? c.toUpperCase() : c.toLowerCase())
            .join(''))
        .join(' ')
}

Answer №2

Try this alternative solution that builds on your existing method by utilizing the .split() function to break down the input string into individual words before proceeding with capitalization of each character.

function convertToOddUpperCase(string) {
  const words = string.split(' ');
  const convertedWords = [];

  for (const word of words) {
    let newString = '';

    for (let i in word) {
      if (i % 2 === 0) newString += word[i].toUpperCase();
      else newString += word[i].toLowerCase();
    }

    convertedWords.push(newString);
  }

  return convertedWords.join(' ');
}

console.log(convertToOddUpperCase("Sample")); // "SaMpLe"
console.log(convertToOddUpperCase("Another sample text")); // "AnOtHeR SaMpLe TeXt"

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

During a submission attempt, Formik automatically marks all fields as touched

I'm facing a problem where a warning is displayed when I try to submit a form because every field is marked as formik.touched=true - this warning should only appear when the name field is changed. I've attempted to remove/add onBlur (some online ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Storing data with NPM global packages: Best practices

I have developed a global npm package that functions as a CLI tool. https://i.sstatic.net/PdT3Z.png My goal is to customize the user experience by having the package remember the user's previous choices. For example, if the user selects 'Iphone ...

Encountering difficulties displaying navigation interface with react native navigation's stack navigator

I am trying to implement a custom side navigation bar in React Navigation without using drawerNavigator. I have fixed the side nav bar and bottom bar in app.js so that they appear on all screens. The main content area should change based on button clicks o ...

Why is it that servlets are unable to send custom JSON strings, and why is it that Ajax is unable to receive them?

I have developed a servlet that responds with a simple JSON list: public void addCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.log(Level.INFO, "Adding the category"); ObjectifyS ...

"Learn the process of sending a post request using a combination of JQuery, Ajax

I am attempting to send a post request with the following code - var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { $scope.data = {}; $scope.reqCalling = function () { ...

Obtain the selected row's ID by leveraging angular.js with either ngSelect or ngOptions

I'm currently working on an angular.js project where I have a dynamic table displaying study results. I want to enhance this by allowing users to view more detailed data about each specific study when they click on the corresponding row in the table. ...

Applying jQuery to deactivate blank categories within a sorted directory

I'm in the early stages of learning Javascript/jQuery. I have a list of items (specifically, course offerings) arranged in a UL. Each "course" is represented by an LI element. The list is filtered by categories using jQuery, which controls the visibil ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Determine whether a component is linked to an event listener

If a <Form> component is called with a @cancel event listener attached to it, the cancel button that triggers this event should be visible. If no @cancel event is present, the cancel button should not be displayed. Is there a method to verify if a c ...

What is the best way to eliminate the ng-hide class dynamically in AngularJS?

https://i.sstatic.net/ShZ3n.pnghttps://i.sstatic.net/n7UsG.pngI need to implement the image upload feature and facing an issue <div class="container responsiveImageSet"> <div ng-show="imageLoader" style="text-align: center;"> <img cla ...

Disregard all numbers following the period in regex

I have developed a function to format numbers by adding commas every 3 digits: formatNumber: (num) => { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') }, The issue with this function is that it also add ...

Confirm data entry upon modification in a dynamic Vue list

When a value is selected from a drop-down menu in the range of 1-10, the system displays a corresponding number of rows (N = value of dropdown). Each row represents an object with three properties: x, y, z. All the created rows are stored in an array, res ...

Implementing Jquery to Repurpose a Function Numerous Times Using a Single Dynamic Value

Important: I have provided a functional example of the page on my website, currently only functioning for the DayZ section. Check it out here Update: Below is the HTML code for the redditHeader click event <div class="redditHeader grey3"> & ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

Encountering Error: When Running the Command "npm run dev" it's Showing "missing script: dev" Message

I attempted to set up the SVELT GitHub repository locally by following these steps: https://github.com/fusioncharts/svelte-fusioncharts When I tried to launch it using the "npm run dev" command, I encountered this error: npm ERR! missing script: dev To ...

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...

Mastering the art of curating the perfect image for your Facebook timeline

Controlling the Like image presented on Facebook timeline can be done using the header element. In my single-page app, I have multiple like buttons, each should be connected to a different image. What is the best way to associate a specific image with e ...

Tips for submitting a checkbox value even when it is disabled

I attempted to make the checkbox readonly, but users were still able to check/uncheck the field. Next, I tried disabling the checkbox which successfully prevented user interaction. However, when attempting to submit the form, the disabled checkbox value ...

jquery personalized auto-suggest

I have multiple input[type="text"] elements with the class .autocomp. When I search for something, PHP retrieves data from a MySQL database and displays it in HTML format using jQuery. My question is, what is the most effective approach among these option ...