Dividing a string by a specified array element in Javascript

Given a string "asdlfjsahdkljahskl" and an array [1,2,3,1,7,2,1,2], the final output should be a, sd, lfj, s, ahdklja, hs, kl.

I'm able to split the string, but I'm unsure how to compare the string and cut it according to the given array.

Here's the HTML code:

<button onclick="myFunction()">click me</button>
<p id="demo"></p>

JavaScript:

var width = [1,4,2,6,1,1,10,1];

function myFunction() {
    var str = "abcdefghijklmnopqrstuvwxyz";
    var res = str.split("");

    for(var j=0; j.length;j++){
        document.write(width[j]);
    }
    document.getElementById("demo").innerHTML = res;
}

Thank you for your assistance!

Answer №1

To extract substrings from a string based on predefined lengths, you can use either the JavaScript array's map method or a for loop.

var string = "asdlfjsahdkljahskl",
    array = [1, 2, 3, 1, 7, 2, 1, 2],
    p = 0,
    result = array.map(function (a) {
        return string.slice(p, p += a);
    });

console.log(result);

You can achieve the same outcome with a for loop as well.

var string = "asdlfjsahdkljahskl",
    array = [1, 2, 3, 1, 7, 2, 1, 2],
    p = 0,
    i = 0,
    result = []

for (i = 0; i < array.length; i++) {
    result.push(string.slice(p, p + array[i]));
    p += array[i];
}

console.log(result);

Answer №2

let str = "asdlfjsahdkljahsxkl",
          arr = [1,2,3,1,7,2,1,2];
      function myFunction() {
          arr.forEach(function(idx) {
              let value = str.slice(0, idx);
              console.log(value);
              document.getElementById("display").innerHTML += value+'\n';
              str = str.slice(idx, str.length);
          });
      }
<button onclick="myFunction()">Click Me</button>
            <p id="display"></p>

Answer №3

If you are looking for an alternative approach to handling strings, consider converting your string into an array and utilizing the .splice() function in the following manner:

let str = "asdlfjsahdkljahskl",
  arr = [1, 2, 3, 1, 7, 2, 1, 2];

function extractValues (str, strLens) {
  str = str.split("");
  strLens.forEach(function (strLen) {
    console.log(str.splice(0, strLen).join(""));
  });
}
extractValues(str, arr);

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 it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

Encountering the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" while using Django and Vue on my website

While working on my project that combines Vue and Django, I encountered a persistent error message when running the code: "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yel ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

Fade background when the youtube video in the iframe begins playing

Hey there! I'm looking to create a cool effect on my (wordpress) site where the background dims when a YouTube video starts playing. The video is embedded in this way: <iframe frameborder="0" width="660" height="371" allowfullscreen="" src="https ...

Issue with jquery's .load() and getScript functions

Earlier today, I encountered an issue with a .load() function being called in a script. I managed to solve the problem using .getScript(), but now I'm facing a major issue - the function is being executed multiple times. You can find the full code a ...

Is there a way to implement a feature that automatically closes the chatbot when the user clicks outside of it?

Here is an example of my HTML code: <div class="chatbot chatbot--closed "> <div class="chatbot__header"> <p><strong>Got a question?</strong> <span class="u-text-highlight">Ask Harry</span></p> < ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

Obtain the data from the array and incorporate it into the fresh PHP code

Having a major issue as I am unsure of how to extract values from an array where the value is transformed into the key in a new array. The original array is presented below: Array ( [0] => Array ( [ID] => 250602 ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

Utilizing jQuery's .slidedown alongside Prototype's .PeriodicalUpdater: A Comprehensive Guide

I am currently working on creating an activity stream that automatically updates with the latest entries from a database table every time a new row is added. Right now, I am using Prototype's Ajax.PeriodicalUpdater to continuously check for new entri ...

How is it possible for a variable of type Object to store a reference to an array in Java?

As outlined in section 1.1 of the JLS, it is stated that: An Object variable can contain a null reference or a reference to any object, whether it be a class instance or an array. This implies that Object obj = new Object[10]; is considered valid in Ja ...

Switching images with a click using jQuery

Is there a way to swap out banners (images) when a user clicks on a link? Here are the links: <li><a href="#" id="button1">1</a></li> <li><a href="#" id="button2">2</a></li> The image in question: <img ...

Combining two collections in MongoDB and calculating the total number of documents

I'm seeking guidance on working with mongodb and node.js. I currently have a collection called PIZZA { title: "bacon" } { title: "pepperoni" } as well as another collection named ORDERS { orderid: 1, pizza: "bacon" } { orderid: 2, pizza: "pepperoni ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

Is there a way to retrieve the original JSON string from a GWT JavaScriptObject?

Working with JSONP in my GWT application has presented some challenges. When the server sends a json string, I am able to retrieve it in the form of a JavaScriptObject on the client side. The issue arises when my json data contains complex structures, usi ...

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...

Animate the jQuery display property to show a table without changing any specified spatial dimensions

When utilizing jQuery's $.animate() on an element styled with display:table, any spatial dimensions that are not explicitly specified to change will animate. Check out the fiddle here In the scenario presented, the width is defined for animation, bu ...

Attempting to use jQuery AJAX to submit data without navigating away from the current webpage

Trying to implement the solution provided in this post where I am trying to send data to a PHP page and trigger an action, but unfortunately, it seems to just refresh the page without any visible outcome. Even after checking the network tab in the element ...

I'm unable to locate my test text on the main page of my React web application

At the moment, my React application is running on port 3000 using npm start. I have made the decision to incorporate MySQL into the web app by executing yarn add express mysql. In order for this to work, I have configured server.js to listen on port 3001 ...