['a', 'm', 'r', 'i', 't', ' ', 's', 'h', 'a', 'h', 'i'], Every time there is a space in a word, it should be displayed. But there is an issue displaying the second word shahi

Is it possible to display the word shahi as the first word and amrit after '', but is there a way to display the last word using code? Any help would be appreciated.

function cap(cht){
         var part1 = [];
         var data = cht.split("")  //['a', 'm', 'r', 'i', 't', ' ', 's', 'h', 'a', 'h', 'i']
         for (var i = 0; i<data.length; i++){
            if(data[i] === ' '){
                break;
            }
            part1.push(data[i]);
         }
         console.log(part1)
     }
     document.write(cap('amrit shahi'));

Output: ['a', 'm', 'r', 'i', 't']

Similarly, I would like to display "shahi" if I console log it.

Answer №1

To properly capitalize each word in a given phrase, you can follow this method:

  1. Utilize an array to store the capitalized words
  2. Have a temporary buffer to hold sub-words

When encountering a space (and the buffer is not empty), add the buffered word to the results and clear it. Any other character should be added to the buffer. Once you reach the end of the input and the buffer is still holding some characters, add it to the final capitalized words.

Note: Instead of using the split function on the string, you can access individual characters using str[index] or str.charAt(index).

Edit: Implemented capitalization for better readability

const capitalizeWord = (buffer) =>
  buffer[0].toUpperCase() + buffer.slice(1).join('');

const toTitleCase = (phrase) => {
  const results = [], buffer = [];
  for (let i = 0; i < phrase.length; i++) {
    if (phrase[i] === ' ') {
      if (buffer.length) {
        results.push(capitalizeWord(buffer));
        buffer.splice(0, buffer.length);
      }
    } else {
      buffer.push(phrase[i]);
    }
  }
  if (buffer.length) {
    results.push(capitalizeWord(buffer));
  }
  return results.join(' ');
};

console.log(toTitleCase('amrit shahi'));

You can enhance the above logic by transforming the conditional statements into a switch case structure for improved clarity:

const CHAR_SPACE = ' ';

const capitalizeWord = (buffer) =>
  buffer[0].toUpperCase() + buffer.slice(1).join('');
  
const toTitleCase = (phrase) => {
  const results = [], buffer = [];
  for (let i = 0; i < phrase.length; i++) {
    switch (phrase[i]) {
      case CHAR_SPACE:
        if (buffer.length) {
          results.push(capitalizeWord(buffer));
          buffer.splice(0, buffer.length);
        }
        break;
      default:
        buffer.push(phrase[i]);
    }
  }
  if (buffer.length) {
    results.push(capitalizeWord(buffer));
  }
  return results.join(' ');
};

console.log(toTitleCase('amrit shahi'));

Answer №2

function capitalizeLetters(text){
         var part1 = [];
         var data = text.split("")  
         for (var i = 0; i<data.length; i++){
            if(data[i] === ' '){
                break;
            }
            part1.push(data[i]);
         }
         return "Capitalized Output: ["+part1.join('","')+"]"
     }
     document.write(capitalizeLetters('amrit shahi'));

Answer №3


    function capitalizeFirstLetter(str) {
      str = str.split(" ");

      for (var i = 0, x = str.length; i < x; i++) {
        str[i] = str[i][0].toUpperCase() + str[i].substr(1);
      }

      return str.join(" ");
    }
    
    document.write(capitalizeFirstLetter('John Doe'));
  

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

Guide on extracting only numerical data from an array of objects for the purpose of calculating total amounts. Unveiling the challenge of building an

I am new to JavaScript and in need of assistance with a particular challenge. How can I extract the "numbers" only from an array containing object values, sum them up, and display the total? Below is the code related to this query; everything that follows ...

Utilize Array.filter to retrieve specific values based on a defined number of elements

I have a function that currently retrieves the url value for each item in an array up to a specified maximum number. Below is the code snippet: const myArray = [ { url: "example.com/1", other: "foo" }, { url: "example.com/s ...

Retrieve Data from HTML Table using jQuery

I am working with an HTML table that has the following values: <tr class="tuker1"> <td class="tuker-lft1"> Username </td> <td class="tuker-rght1" onclick="awardRoute()"> <a href="#"> AWARD ROUTE </ ...

Developing a state object encompassing all the columns of a data table for sorting purposes in React JS

Trying to create a state object to maintain field names and sorting types (ascending/descending). Implementing server-side sorting by passing the column name and sort type (asc or desc). I have a component for a data table with click handlers to determin ...

Application crash imminent, alert: Uncaught TypeError detected - Unable to access property 'some' of undefined within React

My application has 3 sections. The first section consists of a form where users fill in details about watches, and the data is submitted using the submitHandler function. In the second part, users can enter watches from the first section. When a user click ...

Can we create modules with self-invoking functions that are assigned to variables in JavaScript?

Is it possible to assign a self-invoking function module to a variable so that calling the variable will trigger the function without using the () operator? I am looking for the variable to always hold the latest value based on the code inside the function ...

Sorting items in backbone.js can be achieved by using the sortBy method

Currently, I am delving into learning backbone.js and have decided to create my own Todo application using backbone.js along with a local storage plugin. At this point, I have successfully developed the Todo app where you can add and remove tasks. However, ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Screen JSON data by applying filters

In my current project, I am working on extracting data from a JSON file and presenting it to the user in a way that allows them to input values that match the expected data. My goal is to show different sections of the screen at different times. The initi ...

Guide to sequentially playing multiple video objects with buffering

As I work on developing a reference player application that utilizes node.js, javascript, and HTML5, I have encountered an issue. Currently, my player successfully loads a single video and generates diagnostic data from it. However, I am striving to enhanc ...

What could be the reason for fetch failing to reach a node.js route consistently?

I am currently developing a nodejs server with the purpose of providing images to my frontend. In order to achieve this, I am utilizing fetch to retrieve data from my express routes. However, I have noticed that fetch does not consistently pull in the data ...

Troubleshooting a Global Search Problem with Regular Expressions in Javascript

I am facing a minor problem. Here is the snippet of code I am working with: var result1=content.match("/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi")[1]; This code is not returning any value. Al ...

Which specific graphing library does GitHub utilize for its Graphs section?

Which graphing library is utilized by GitHub on its Graphs tab? The graphs displayed at https://github.com/USER/REPOSITORY/graphs/commit-activity are visually appealing, detailed, and adaptable. If they are leveraging an open source javascript library fo ...

Is it feasible to merge Apollo queries within the context of Nuxt?

Incorporating nuxt and apollo together using the https://github.com/nuxt-community/apollo-module module has been a successful venture. A GraphQL query was crafted and tested in GraphiQL to obtain information about a specific page along with general SEO de ...

The connection between MongoClient and Express has been established successfully, however, an error occcurred: TypeError: Cannot read the property 'collection' of null

I am currently working with the MongoClient instead of mongoose, but I am facing an issue where I can't seem to set a new collection in my routes file. db/index.js const {MongoClient} = require('mongodb'); const MONGO_DB_NAME = 'mooo ...

An error is thrown when trying to retrieve Objects: Uncaught TypeError - Object function ParsePromise()

By obtaining a Document object with its id, the following code proceeds to locate corresponding sections based on the object. The document identifies a Parse object and document.toJSON converts this into a Javascript object. Furthermore, sections represent ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

Configuration of HTTP JSONP variable in Angular

I have successfully implemented http.jsonp for making cross-domain calls. Here is the configuration object I am using: var config = { params: { action: "query", prop: "revisions", format: "json" ...

Error in VueJS when attempting to call a method within a v-for loop: 'not defined on the instance but referenced during render'

I’m still getting the hang of Vue.js (Vuebie?), and while I know this question has been asked before, I’ve not quite stumbled upon a solution myself. My current challenge involves passing an object to a method in order to increment a value and then di ...

Looking for a specific string within a 2D array in Python by iterating either to the right or

I am working with two arrays, one containing strings and the other containing words: l = ["abc", "def", "hij", "klm", "nop", "qrs"] word = ["abc","knq","knop"] I need to search for each word in the list and return the correspon ...