Incrementally Increasing Array Elements with Javascript's Splice Method

I'm attempting to insert "-" before capital letters in a string. For example, transforming helloWorld into hello-world.

Despite my efforts, the dashes are being placed incorrectly within the output array. For instance, changing thisIsSpinalTap to this-I-sSpin-alTap

What could be causing this issue with my code?


function spinalCase(str){
    str = str.replace(/ /g,'-');
    strArr = str.split("");
    
    for(i=1;i<str.length;i++){
        if(str.charAt(i)==str.charAt(i).toUpperCase()&&str.charAt(i)!=="-"){
            console.log(i);
            strArr.splice(i,0,"-");
        }
    } 
    return strArr.join("");
}

spinalCase('thisIsSpinalTap'); // should give this-I-sSpin-alTap 

Answer №1

The issue lies in the fact that every time a splice is performed, strArr shifts to the left; therefore, it is advisable to maintain an additional counter starting at 0 and incrementing each time a splice is executed, like so:

var k = 0;
// ...
    strArr.splice(i + k, 0, '-');
    ++k;

If you are not simply practicing, there is a simpler method available:

var s = 'thisIsSpinalTap';

var res = s.replace(/([a-z])([A-Z])/g, '$1-$2'); // "this-Is-Spinal-Tap"

This expression identifies a lowercase letter followed by an uppercase letter and substitutes it with a dash in between.

Answer №2

One issue arises when modifying the array within a loop while checking characters using a string that does not reflect the updates made to the array due to new character insertions. As a result, when a - is inserted, the indexes in the string lag behind those of the array by 1 position, leading to incorrect placements of -. This pattern persists with each insertion, causing the third insertion to occur at position-2.

function spinalCase(str) {
  str = str.replace(/ /g, '-');
  var strArr = str.split(""),
    i, code;
  for (i = 1; i < str.length; i++) {
    //since we are modifying the array the indexes in the original array can't be used
    code = strArr[i].charCodeAt(0);
    if (code >= 65 && code <= 90) {
      strArr.splice(i, 0, "-");
      //since we are inserting a new element before current element we need to skip an extra element
      i++;
    }
  }
  return strArr.join("");
}

var result = spinalCase('thisIsSpinalTap');
snippet.log(result)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

The jQuery window.on event is not functioning when trying to handle the same hash change

How to fix jQuery window.on hashchange issue when clicking on the same hash? See the code snippet below for a potential solution: function addMargin() { let header = $('.header__wrapper').outerHeight(); let headerHeight = $('body& ...

What is the method for implementing absolute paths rather than relative paths in a React or Next.js project?

In my React project, I frequently use multiple components within various higher-order components. This often leads to long import paths like import MyComponent from '../../../../components/MyComponent'. I am aware that there is a more efficient w ...

Creating a dynamic image collage with scrolling bubbles: A step-by-step guide

I'm excited about creating a unique scrolling image collage with image bubbles! I want something similar to this The design is ready, but I need help implementing the auto carousel slider effect to make the images slide continuously. Can anyone assi ...

React JS component experiencing issues with Material UI modal functionality

Attempting to reproduce the material ui modal example has proven to be a challenge for me. Initially, I encountered an error stating "Cannot read property 'setState' of undefined" which I managed to resolve. However, even after resolving this iss ...

Is it a beneficial strategy to remove object keys and assign new keys when iterating through thousands of objects in a loop?

Consider the following array as an example: For instance var a =[{name :"Adi", age:23},{name:"aman" ,age : 23},{name : rob,age:52}]; Is it better to delete the keys 'name' or assign them as undefined? Which approach is more efficient? Does us ...

What is the best way to input two distinct variables into the Firebase database?

I have encountered an issue while trying to upload two variables into my Firebase database. Only the first variable, newRoute, is being successfully uploaded while new User isn't getting uploaded. The setup of the Fire configuration for the entire web ...

JQuery is not recognized by Ajax components

When I add new buttons and information to my PHP page using jQuery Ajax, the problem arises when I click on these new buttons. The jQuery associated with the new buttons does not work, while the jQuery for old buttons still works. It seems that the new but ...

Utilizing Firebase authentication and next-auth in Next.js - Authentication currently returns null

I'm creating a website with nextjs 13 (app router) and incorporating firebase. I've come across suggestions to combine next-auth and firebase auth for using firebase auth effectively. Accordingly, I have configured my firebase Here is the fireba ...

"Using Three.js GLTF, switch the material of one object to match the material of

Recently, I encountered an interesting challenge with a scene imported from a glb-file using GLTFLoader. The scene features various objects of guys in different colors, each with its own material (RedMat, BlueMat, GreenMat, etc) created in Blender. Interes ...

Just updated to Angular 10, encountered issue: Unable to modify the read-only property 'listName' of an object

After updating my Angular project from version 8 to version 10, I encountered an error while trying to edit an input field in a Material Dialog. The error message displayed is as follows: ERROR TypeError: Cannot assign to read only property 'listName& ...

What is causing my function to not wait for the resolution of the Promise?

checkout.ts updateGlobalValue(){ updateShadowDomButton(); let globalValue = fetchGlobalValue() } web_component_render.ts let globalValue; async fetchData() { let booleanFromApi = await callToExternalAPI(); return booleanFromApi; } functi ...

display the values of the array object within the ajax success callback

When I receive the result, it looks like this https://i.sstatic.net/q4iUb.png But now I want to display that content inside a dropdown box with option values. How can we accomplish that? My current approach is as follows: var data = data.user_contacts ...

Why does the arrow function get executed right away once it is wrapped?

Currently, I am working on developing an app using react native. The goal is to have the screen automatically advance to the next one if there is no touch response within 5 seconds. I have implemented a function where pressing a button or entering text wi ...

[ERROR_HTTP_HEADERS_ALREADY_SENT]: Headers can't be set once they have been sent to the client, expressjs

Whenever I attempt to insert data into my MySQL database using the express router function, I encounter an error. It appears that my server is trying to send a response twice, but I am unsure of where the issue lies. Here is the error message: throw err; / ...

Changing an array of character pointers to lowercase in the C programming language

I am facing an issue with converting all the strings in my char pointer array to lowercase. Here is what I have attempted so far: char* wordArray[ARRAY_MAX]; In order to convert each string to lowercase, I initially looped through the array and used a p ...

Explain the process of data binding with DOM elements

I'm intrigued by how jQuery has the ability to link arbitrary data with any DOM element without the use of HTML data attributes. $('#div_id').data('suffix', (count++)); In the Firebug HTML snapshot, I don't see any data attr ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

Tips for displaying "No Results" without causing any lag in the browser

I'm encountering difficulty trying to implement a simple feature without resorting to a "messy" solution. The performance is suffering, and I am certain it's not done in a "professional" manner. What I desire is straightforward – displaying a ...