Modifying the index value within an array

I am facing a challenge where I must remove a letter from each element in an array and alter the first letter if it is at index 0. My current strategy involves the following code:

function capital(arr, char){
    let str = "";
    let result = "";
for (let i = 0; i < arr.length; i++){
    str = arr[i] + (i < arr.length - 1 ? ",": "");;

    for (let j = 0; j < str.length; j++){
        if (str[j] === char){
            result += "";
             if (str[j] === char){
            result += (j === 0? "A": "");
        }
        
        else {
            result += str[j];
        }
    }
}
    console.log(result);
}
capital(["doritos","sandking","bandana", "demand"], "d");

This program aims to eliminate all instances of the letter 'd' in the strings and change the first letter to 'A' if 'd' is at index 0.

The current output is

Aoritos,sanking,banana,Aeman

However, the desired result should be

Aritos,sanking,banana,Aman

The condition is that built-in functions cannot be used, and the program needs to be case insensitive. I can work on addressing these concerns by tweaking the code and adding conditional statements, but I need help specifically with ensuring the modification to index 0. Any assistance would be greatly appreciated. Thank you!

Answer №1

To determine if the character in your input is located at the beginning of a string, you can use str.indexOf(char). If it is found at the first index, add the prefix "A" to the string without the first character using str.substring(1).

function capitalizeFirst(arr, char) {
  let str = "";
  let result = "";
  for (let i = 0; i < arr.length; i++) {
    str = arr[i];
    if(str.indexOf(char) === 0) {
      result = 'A' + str.substring(1);
    } else {
      result = str;
    }

    console.log(result);
  }
}
capitalizeFirst(["doritos", "sandking", "bandana", "demand"], "d");

Answer №2

Consider this approach

function replaceFirstLetter(arr, char) {

  return arr.map(e => {

    let isFirst = false;
    if (e[0] == "d") isFirst = true;
    e = e.replace(new RegExp(char, 'ig'), '');
    if (isFirst)
      e = e.replace(e.charAt(0), "A");
    return e;
  });

}
console.log(replaceFirstLetter(["doritos", "sandking", "bandana", "demand"], 'd'))

Answer №3

To update the first letter of a word when it matches a passed letter at index 0, iterate through each letter and add non-matching letters to the result.

const capitalize = ch => {
 const letter = ch.charCodeAt(0);
 if(letter >= 97 && letter <= 122) {
    return String.fromCharCode(letter - 32);
 }
 return ch;
}

const capital = (words, ch) => {
  let result = '';
  for(let i = 0; i < words.length; i++) {
    let newWord = '';
    for(let j = 0; j < words[i].length; j++) {
      if(capitalize(words[i][j]) === capitalize(ch) && j === 0) {
        newWord = 'A';
      }
      if(capitalize(words[i][j]) !== capitalize(ch)) {
        newWord += words[i][j];
      }
    }
    result += newWord;
    if(i < words.length - 1 ) {
      result += ',';
    }
  }
  return result;
}

const result = capital(["doritos","sandking","bandana", "demand", "sandDking"], "d");
console.log(result);

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

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Accessing properties in JSON data with AngularJS

I am experiencing issues with accessing a JSON object returned from an $http call in my AngularJS app. I have provided the code snippet below, but it seems that nothing is being rendered on the HTML. Can anyone please assist me in identifying what I might ...

Tips for creating a concise switch statement in JavaScript, incorporating both the use of Express and Mongoose

Here's the current situation: I am tasked with searching in 3 different databases for an ID associated with a shift. Each shift is classified as either an Activity, Food and Beverages, or Other type. When making the search, the type is provided in t ...

How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one. Here is my current code snippet: const input = ...

Unable to perform real-time transpilation of ES module, a loader plugin must be set up through the SystemJS.config configuration

I encountered an issue while trying to develop a plugable application. Everything was functioning correctly until I introduced "ngx-bootstrap" and "FullCalendarModule"/primeng in the plugin app. Importing any of these modules resulted in the following erro ...

The select2 ajax functionality encountered an error: Uncaught TypeError - Unable to access the 'context' property as it is undefined

Trying to make an AJAX request using the Select2 jQuery plugin. The query appears to be functioning properly, but the problem arises when ".context===undefined" is called on the "data" object: Uncaught TypeError: Cannot read property 'context' o ...

Is it possible to set up a PHP variable within a JavaScript function?

In the code snippet above, we have a JavaScript function that is used for validation. I am looking to set a PHP variable within the else statement. function validate() { if(document.loginForm.vuser_login.value==""){ alert("Login Name name ca ...

Tips on avoiding blurring when making an autocomplete selection

I am currently working on a project to develop an asset tracker that showcases assets in a table format. One of the features I am implementing is the ability for users to check out assets and have an input field populated with the name of the person author ...

Sketch a ring outlining the clusters of nodes

I am working with a vis-network in which I have divided nodes into 2 groups - left and right. I achieved this by arranging the node positions using layput_as_tree. Now, I want to visually distinguish these groups by drawing a circle or ellipse around the ...

The onChange functionality of the Formik Field API is not compatible with a child component

I am currently facing an issue with validating a material-ui-dropzone component within the Formik Field API as a child component. When I try to upload a file, I encounter the following error: TypeError: can't access property "type", target is undefine ...

jQuery Mobile's photo swipe with target feature isn't functioning as expected

Utilizing Photo Swipe ( ) on my jQuery Mobile page. I aim to display a thumbnail view of the images upon loading. When clicking on a thumbnail, the user should be taken to a swipe-enabled gallery that takes up 30% of the screen height. Additionally, I wan ...

Tips for transferring JSON information instead of displaying it in the console

Currently developing a food ordering application using Flutter along with an API built in Express.js and MySQL for the database. I have successfully connected to the database, received JSON data, and logged it using console.log(), but I am struggling with ...

Determining if a swf file has loaded using JavaScript and swfobject

Here is the code snippet I am working with: <head> # load js <script> function graph() { swfobject.embedSWF( "open-flash-chart.swf", "chart", "400", "180", "9.0.0", "expressInstall.swf", {"data-file":"{% url moni ...

HTML element resizing unexpectedly due to browser interactions

I recently created a sleek HTML transparent header bar using the following CSS: #head-bar{ position:fixed; top: 0px; width:100%; left:0px; min-height:25%; z-index:2; background-color:#000; background: rgba(0, 0, 0, 0.5); } ...

Create a function that identifies and returns the greatest value out of a set of four numbers

In my quest to determine the greatest among four numbers using JavaScript, I came across the following code snippet. My exploration on how to achieve this task mainly revolves around array options instead of utilizing individual variables for numbers. fu ...

Steps to take to save an HTML element as a PNG

Unique content: I am looking to convert a standard HTML element into an image on an HTML canvas for my website project. I am currently working on creating a website that involves displaying various elements on the screen. One of the key requirements is b ...

Using jQuery to modify the contents of a div in real-time is resulting in the loss of HTML encoding

I have come across a situation where I am dynamically changing the HTML content of a div called 'accordion' using the following code: // The variable htmlstring contains some HTML code with special characters like &, ', etc. // For example: ...

It is not possible to utilize PopOver within the Header Menu Item

I am looking to create a header with a popover component. import React from "react"; import { Layout, Menu, Button } from "antd"; const { Header, Popover } = Layout; const { SubMenu } = Menu; const Index = (props) => { const content = ( & ...

Guide to fetching the title image and content using AJAX in PHP

How can I effectively display the title, image, and content data? Take a look at the code snippet below: view.php $id = $_REQUEST['edit_literature_id']; $literature = $_REQUEST['literatureID']; $module = $_REQUEST[&ap ...