Using the splice technique to include a new element

I have been attempting to use the JavaScript splice method to insert a "-" before each capital letter in my array, but it doesn't seem to be working as I expected. I'm not sure where I am going wrong. Below is the code that I have written:

function spinalCase(str) {
  let strArr = [];
  for(let i = 0; i < str.length; i++){
    strArr.push(str[i]);
  }
  for(let i = 0; i < strArr.length; i++){
    if(strArr[i] !== strArr[i].toLowerCase()){
      strArr.splice(strArr.indexOf(strArr[i]),0, "-");
    }
  } 
console.log(strArr);
}

spinalCase('thisIsSpinalTap');

Answer №1

By adding a new element using the splice method, the array's length increases and causes the loop to never reach its end. To avoid this issue, it is recommended to iterate through the array from the end to the beginning.

function convertToSpinalCase(str) {
  let strArray = [];
  for (let i = 0; i < str.length; i++) {
    strArray.push(str[i]);
  }

  // Iterate through the array from the end to the beginning
  for (let i = strArray.length - 1; i >= 0 ; i--) {
    if (strArray[i] !== strArray[i].toLowerCase()) {
      strArray.splice(strArray.indexOf(strArray[i]), 0, "-");
    }
  }
  console.log(strArray.join(''));
}

convertToSpinalCase('thisIsSpinalTap');

Answer №2

Although you were considering using splice, allow me to present a regex solution as an alternative.

function hyphenateCamelCase(str) {
 return str.replace(/[A-Z]/g, "-$&").toLowerCase();
}

console.log(hyphenateCamelCase("thisIsSpinalTap"))
// this-is-spinal-tap

Answer №3

Altering your array occurs when you perform the following action:

strArr.splice(strArr.indexOf(strArr[i]),0, "-");

As a result, the length of strArr is not consistent within the loop

for(let i = 0; i < strArr.length; i++)

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

Is there a way to verify the existence of a key within server data using Javascript?

When receiving JSON values from the server, there is uncertainty about whether a particular field will be included or not. At times, the response looks like this: { "regatta_name":"ProbaRegatta", "country":"Congo", "status":"invited" } While other ...

Ensure that each class element contains a value before using jQuery to toggle the disabled class

I'm having trouble validating the values of the input elements in my form. I can't seem to figure out what I'm doing wrong. Can anyone help me out? Thank you. <div class="form--group"> <input class="thename" name="name[]" type= ...

Tips for displaying JSON data within another array in a Bootstrap table

I'm working with the following JSON data that I need to display in a bootstrap table. I can easily display the single-level data, but I'm unsure how to display array within array data in the bootstrap table. [ { "seriesName": "Indian ...

Verify whether an item is present in a jquery assembly

When initializing a jQuery collection, I start by doing $collection = $([]) As events unfold later on, I find myself frequently using $collection = $collection.add($element) This approach allows me to easily call functions like $collection.hide() on al ...

What is the best way to update an element in an array inside a JavaScript object

In my NodeJS code, I have an object structured like this: const jsonData= { "description": "description", "hosts": [ "host1", "host2", "host3" ] } The task at ...

What are the methods for removing the color green with CSS or JavaScript?

Is it possible to isolate only the red and blue color components in an image or text using CSS 'filter' feature? If so, can someone please provide guidance on how to do this? Thank you. ...

Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my ...

Run JavaScript code when the HTML file has been modified for the second time

After browsing through this online forum, I stumbled upon a helpful solution. See the code snippet below for reference. However, I encountered a problem in my case. The script in question is essentially monitoring itself. The code resides in index.html an ...

"The server is refusing to process the request because it does not allow POST methods, only GET methods are

After successfully creating a web api in ASP.NET Web API, I encountered an issue when accessing the site hosted on Vercel. While the GET methods worked fine, the POST methods did not. This was due to the backend API being on my local system, causing a conf ...

What is the best way to establish the render() method for an 'arrow' component?

I came across the following code snippet: const CoolComponent = props => { ... I am looking to add a render() function to it: render() { console.log('Hello world'); return ( <Bar foo={true} {...propz} ...

Warning in Vue.js: Duplicate keys with the value of '0' have been detected, which could potentially lead to update errors. This issue was found within the Vue.js Bootstrap collapse

When trying to create a collapsed card with Bootstrap 4 and Vue.js, I encountered some issues. Bootstrap 4 was functioning properly without Vue.js, maintaining the proper transitions and not expanding cards that were not clicked. However, after moving my c ...

Waiting in Python using Selenium until a class becomes visible

Currently, I am trying to extract information from a website that has multiple web pages. This is how my code appears: item_List = [] def scrape(pageNumber): driver.get(url + pageExtension + str(pageNumber)) items = driver.find_elements_by_class_ ...

What is the best way to pass individual values from an array as arguments to a function?

Here is a function that can take in multiple integer parameters and return their sum: int calculateSum(int num, ...){ va_list numbers; va_start(numbers, num); int result = 0; for(int i=0; i<num; i++) { result += va_arg(numbers, i ...

The dialog box is refusing to appear as a modal popup - shadcn

I recently integrated the Dialog component from shadcn into my next.js project. However, I am encountering issues as it is not behaving like a typical modal or popup. Here is a screenshot for reference: https://i.sstatic.net/fVkQz86t.png return ( < ...

JavaScript's prime sleep function

I am in need of a sleep function for my JavaScript code. I could use a promise-based function, but it requires the await keyword to function correctly. The issue is that I need to use the sleep function at the top level of my code. function sleep(milliseco ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

Exploring Websites Using Javascripts or Online Forms

I am currently facing a challenge with my webcrawler application. It has been successfully crawling most common and simple sites, but I am now dealing with websites where the HTML documents are dynamically generated through forms or JavaScripts. Even thoug ...

Learn how to add a variable to a PHP array using a jQuery click event

The following button is what we're working with: <button id="animals" type="button" value="push" >Push</button> In my PHP array, I currently have: $animalArray = array($dog, $cat, $horse, $lamb, $fox); Here is the jQuery code snippet t ...

What is the best method for finding a particular value in a generic List in C#?

class MyGenericClass<T> where T : ICompareable { T[] data; public AddData(T[] values) { data = values; } } Within my application's primary form, I generated three random numbers and assigned them as values: 1 3 3, resulting in: T ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...