Is there a way to divide a string into an array based on my loop iteration in JavaScript?

My goal is to break a string into an array during each iteration of my for-loop. For example, if the string is "1234", I want it split as ['12', '34']."

I am looking to explore different ways of splitting this string such as ['1', '2', '3', '4'], ['123', '4'], etc. However, I'm unsure how to achieve this.

The string "31173" can be divided into prime numbers in 6 ways:

[3, 11, 7, 3]
[3, 11, 73]
[31, 17, 3]
[31, 173]
[311, 7, 3]
[311, 73]

let k=1;

for(let i=0; i<inputStr.length; i++){
        
if(k<inputStr.length){
    // splitting the string 
    let splittedNums=inputStr.split('',i+k);
    for(let j=0; j<splittedNums.length; j++){
       if(isPrime(splittedNums[j]))
          result.push([splittedNums[j]]);
        
      }
   }
 k++;
}

I attempted to use the split() function but found from the documentation that it has limitations when splitting and returning the string, making it unsuitable for my requirements.

My aim is to split the string, check if the resulting number is prime, and then store it in an array. Ultimately, I intend to gather subarrays containing only prime numbers.

How can I efficiently split a string and convert it into an array like this in JavaScript?

Answer №1

Here is a solution I came up with. The steps are briefly explained in the comment section:

  1. Start by converting the string into an array.
  2. Iterate through the string array and split it based on each character index.
  3. Add back the lost separator by appending it to the last item of the array.

const str = "12345678";

// splitting the string
const strArr = str.split("");

// iterating through the array and splitting at individual characters
const splitedStr = strArr.map((each, index) => {
    const withoutSeparator = str.split(str[index]); 

  const lastIndex = withoutSeparator.length - 1;

  // adding back the separator to the last element
  withoutSeparator[lastIndex] = str[index] + withoutSeparator[lastIndex];

  return withoutSeparator;
});

console.log({ splitedStr });

Output

{
  splitedStr: [
    [ '', '12345678' ],
    [ '1', '2345678' ],
    [ '12', '345678' ],
    [ '123', '45678' ],
    [ '1234', '5678' ],
    [ '12345', '678' ],
    [ '123456', '78' ],
    [ '1234567', '8' ]
  ]
}

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

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

Fastblox - utilizing javascript SDK for group chatting

I've been facing issues setting up a group chat using QB Javascript SDK. There are a few problems I am encountering: Firstly, I consistently receive a "room is locked" message. Here's the link to the screenshot: https://i.sstatic.net/auR21.png. ...

What causes the strings in an array to be split into individual characters when using the jquery each() function?

After successfully loading jquery, I have initialized an array (object) with various strings: window.stack = [ "header", "nav", ".content", "footer" ]; My intention was to loop through this array using jquery's each() function to retrieve ea ...

Creating a Turn.js interactive book similar to the provided example?

I'm in the process of creating a book using turn.js with Jquery and everything is going smoothly so far. However, I could use some assistance. I am trying to achieve the look of a hard-backed journal-type book similar to the example provided here . My ...

Column header customization in el-table does not update reactively

Working with VueJS version 2.6.10 and Element-UI version 2.12.0, I have successfully displayed data inside an el-table component. Everything is going well so far. I am looking to add input fields in the column headers for filtering the data, but I only wa ...

What is the best way to replace a regular expression in JavaScript?

I've recently been exploring the functionalities of MathJax, a Javascript library that enables the use of LaTex and similar mathematical markup languages within HTML. However, when attempting to incorporate it into my Javascript code, I encountered so ...

localStorage is functional on desktop devices; however, it does not work on mobile devices running iOS version 12

After developing a basic Todos application using React, I decided to introduce the use of localStorage to maintain data persistence between page reloads. Below is an overview of how I implemented it: loadStateFromLocalStorage() { for (let key in this.st ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Convert JavaScript files into JSON files using Laravel

I have a JavaScript file containing key-value pairs as shown below: es.js export default { currency: "Dinero", void: "Vacio", } Now, I need to convert this file into a JSON format. es.json { "currency" : "Dinero", "void" : "Vacio", } W ...

Saving a collection of CustomObjects in UserDefaults

My custom class is defined as Set<ListItem>, and I am trying to store it in userDefaults. However, I am encountering an error that says Attempt to set a non-property-list object as an NSUserDefaults when I attempt to do so. I have tried changing it t ...

An individual array incorporated into a two-dimensional array

Check out this code snippet: #include <stdio.h> #include <math.h> int main() { int d, a[3][3] = {{2, 4, 5}, {6, 7, 8}, {9, 10, 11}}; for (d = 0; d < 5; d++) { printf("a[%d] = %d\n\n", d, a[d]); } ...

Choosing an option in a dropdown menu during ProtractorJS end-to-end testing

I need to automate the selection of an option from a dropdown menu for angular end-to-end tests using protractor. Below is the code snippet for the select option: <select id="locregion" class="create_select ng-pristine ng-invalid ng-invalid-required" ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

React form submissions result in FormData returning blank data

I am having trouble retrieving the key-value pair object of form data when the form is submitted, using the new FormData() constructor. Unfortunately, it always returns empty data. Despite trying event.persist() to prevent react event pooling, I have not ...

Update the standard text in Material-table

Currently, I am implementing Material-table into a project and exploring ways to customize it further. My main focus is on altering the default text like 'search' and 'rows.' Here is a snapshot of how my table appears: https://i.sstati ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

I want to know how to keep additional inline whitespace while using the default JS/TS formatter in VS Code

Take this line, for example: var x = 5; var yyyyy = 10; var zzzzzz = 15; The VS Code Formatter removes the extra spaces between variable names and values. var x = 5; var yyyyy = 10; var zzzzzz = 15; Is there a way to configure it to keep the f ...

Managing dynamic queries can be quite a challenge, but with the right

Basic Inquiry I am trying to work with a table that has the following structure https://i.sstatic.net/klZqE.png My goal is to use a select query to achieve a result similar to https://i.sstatic.net/in7zq.png Could this be related to PIVOT functionalit ...

Populate an array with a series of dates, verify their accuracy, and determine the highest value within

Below are some input fields: <input type="text" name="date_1" class="dataList" value="2009-12-30" /> <input type="text" name="date_2" class="dataList" value="2007-06-12" /> <input type="text" name="date_3" class="dataList" value="2009-10-23 ...

Preventing pop-up windows from appearing when triggered by a mouse click event

I am looking for a solution to trigger a popup window when a user right-clicks on a specific area. Here is the current code I am using: $("#popup").bind('mousedown', function(e) { var w; if(e.which==3) { w=window.open('link& ...