Is there a way to produce a list of array elements where the initial letter is capitalized?

My current challenge involves trying to capitalize the first letter of each element in the following array. So far, it's only returning the second word as capitalized.

var clenk = ["ham","cheese"];
var i = 0;
for (i = 0; i < clenk.length; i++) {
var result = clenk[i].replace(/\b./g, function(m){ return m.toUpperCase(); });

}

alert(result);

Answer №1

let foodItems = ["apple","banana"];
let x = 0;
for (x = 0; x < foodItems.length; x++) {
    let item = foodItems[x].replace(/\b./g, function(m){ return m.toUpperCase(); });
    console.log(item);
}

Make sure to include your console.log(item) within the loop to see each capitalized item.

Answer №2

Another approach using Array.prototype.map:

let transformedWords = words.map(function (word) {
    return word.charAt(0).toUpperCase() + word.slice(1);
});

Answer №3

Extend the JavaScript String object:

String.prototype.toUpperCaseWords = function () {
  return this.replace(/\w+/g, function(a){ 
    return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
  })
}

Example of usage:

"MY LOUD STRING".toUpperCaseWords(); // Returns: My Loud String
"my quiet string".toUpperCaseWords(); // Returns: My Quiet String

var stringVariable = "First put into a var";

stringVariable.toUpperCaseWords(); // Returns: First Put Into A Var

Source

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

"Encountering a problem with installing packages on Node.js through npm

After spending the last 2 hours scouring StackOverflow and Google, I've come to the decision to seek help here. The issue I'm facing is that I'm unable to install any packages using npm. Specifically, when trying to install jQuery (as well ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

Accessing the "this" object in Vue.js components

When executing console.log(this) in the doSomething method, it returns "null". I was expecting console.log(this.currentPage) to display "main", but unfortunately, the "this" object is null.. :( Is there a way to access the value of "main" for currentPage ...

Remove element from associative array in TypeScript

I encountered a code snippet like the one below let failures: Map<string, Array<string>> = new Map([ ['1', ['a', 'b']], ['2', ['c', 'd']], ['3', ['e', ' ...

The debugging functionality in WebStorm version 11.0.4 is currently experiencing problems. Users have reported receiving a warning message stating that the commands node --debug and node --debug-br

Specific warning message: Warning: node --debug and node --debug-brk are no longer supported. Please use node --inspect or node --inspect-brk instead. Node version: 8.9.3 Does anyone know of a workaround to enable seamless debugging in the IDE? Any a ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

Differences between `component` and `render` in React Router routes

Two questions have arisen for me when using Route from react-router-dom(v4.3.1): What is the difference between using component and render in Route: <Route exact path='/u/:username/' component={ProfileComponent} /> <Route exact path ...

Error encountered while trying to send an array list using the $.ajax function in jQuery

My web API expects JSON data in the following format (input parameter) { "districtID": "string", "legendIDs": ["string","string"] } Below is the JavaScript code I am using to build the request: var cityDistrictId = 'fb7b7ecd-f8df-4591-89de-0c9d ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

create hyperlinks based on div clicks in HTML using JavaScript

Hey there! I'm working on a cool animation for my page that involves a star fade effect. After the animation, I want to open a link to another page on my site. Imagine I have 3 cards on my page, and when I click on any of them, I want the same animat ...

Utilizing Highcharts to visualize data from a mysql database through a dynamic Pie Chart

I am currently working on generating a pie chart using highcharts to visualize the distribution of each value assigned to a specific column (TYP_CODE) relative to the total number of entries. synthese.php : <?php session_start(); if(!isset($_S ...

Adjust Tinymce size automatically when a key is held down for a prolonged period of

Having trouble with tinymce not automatically resizing when certain characters are pressed repeatedly. However, the height adjusts after releasing the key. Is there a method to auto resize tinymce during the key down event? I am utilizing angularjs ui-tin ...

Map on leaflet not showing up

I followed the tutorial at http://leafletjs.com/examples/quick-start/ as instructed. After downloading the css and js files to my local directory, I expected to see a map but all I get is a gray background. Can anyone advise me on what might be missing? T ...

Is the security of Angular's REST authentication reliable?

My goal is to establish a secure connection with a REST service using Angular. I have come across the official method, which involves setting the authentication ticket like this: $httpProvider.defaults.headers.common['Authorization'] = 'dhf ...

Uploading Images Dynamically with AJAX

Can someone assist me with a multiple upload form that utilizes AJAX to upload and display an image without the need for a submit button? My issue arises when dealing with repeating forms within table rows, causing only the first form to function properly. ...

Creating Three-Dimensional Faces in THREE.BufferGeometry

I have programmatically created a basic mesh structure: var CreateSimpleMesh = new function () { var xy = [], maxX = 7, maxY = 10, river = [[0, 5], [0, 4], [1, 3], [2, 2], [3, 2], [4, 1], [5, 1], [6, 0]], grassGeometry ...

Verify the grid of buttons in my code for the background color

My goal is to make sure that when all the buttons are black, the h2 text in the 'lightsoff' div is displayed. If any buttons are not black, the text will remain hidden. I plan to achieve this by creating a new function that checks the background ...

Grabbing an AJAX Request

Currently, I am working on a Firefox extension that is designed to analyze the HTML content of web pages after they have been loaded in the browser. While I have successfully captured events like form submissions and link clicks, I am facing an issue wit ...

A guide on utilizing the .getLastRow() function in Google Apps Script

I am relatively new to Google Script and I am currently working on a piece of code that is giving me some trouble. My goal is to have the program loop through a range of cells in a spreadsheet, printing them out until it reaches the last row. Despite try ...

Is there a way to expand jQuery quicksearch functionality to include searching for words with accents?

Hello everyone, I'm currently working on the development of this website using jQuery isotope, WordPress, and jQuery quicksearch. Everything is functioning perfectly, but I would like to enhance its functionality. For example, when I type "Mexico," I ...