Divide a string into an array starting from the end

I have a unique phrase.

var phrase = "LoremipsumdolorsitametconsectetuadipiscingelitSeddoeiusmodtemporincididuntutlaboreetaliqua";

I am interested in dividing it into chunks of 11 characters starting from the end.

Currently, I use:

function splitPhrase(sentence) {
  return sentence.split( /(?=(?:...........)*$)/ ).map(function(segment){return parseInt(segment)});
}

This operation results in:

[L, oremipsumd, olorsitame, tconsectet, uadipiscin, gelitSeddo, eiusmodtem, porincidun, tutlaboret, aliqua]

Queries:

  • How can I modify the above function to make it adaptable for breaking strings into segments of any number of characters? (I prefer not manually adding or removing dots)

  • Is there a way to exclude the first character when splitting the string? (I aim to maintain 'L' as the initial element so the following elements can vary in length from 1 to n)

Answer №1

To specify the number of digits you want for each item, wrap them inside curly braces in the regex. Remember that variables cannot be passed directly to a regex using "/" as delimiters; instead, use the RegExp constructor.

var string = "31415926535897932384626433832795028841971693993751058209749445923078164";
function split(a,n) {
  return a.split( new RegExp("(?=(?:.{" + n + "})*$)" )).map(function(x){return parseInt(x)});
}
alert(split(string, 10))

OR

You can also use the match function instead of split.

string.match(/(?!^.).{11}/gm)

DEMO

var string = "31415926535897932384626433832795028841971693993751058209749445923078164";
function split(a,n) {
  return a.match(new RegExp("(?!^.).{" + n + "}|^.", "gm")).map(function(x){return parseInt(x)});
}
alert(split(string, 11))

If you wish to include the remaining characters, including the initial and unmatched ones at the end, you can utilize this regex pattern.

/(?!^.).{11}|^.|.+/gm

DEMO

Answer №2

Please review the following code snippet:

var _mySplit = function(str, splitLength) {
    var _regEx = '';
    var startSubStringLength = str.length % splitLength
    if(startSubStringLength > 0) {
        _regEx = new RegExp("(^.{1," + startSubStringLength + "})|(.{1," + splitLength +  "})|(.{1,})", "g")
    }
    return str.match(_regEx)
}

Answer №3

Here's a simple solution that does not involve using regular expressions: var string="31415926535897932384626433832795028841971693993751058209749445923078164"; var arr = new Array(); while (!string.length < 10) { substr = string.substr(strlen(string)-10); string = string.replace(substr, ''); arr.push(substr); } var result_arr = arr.reverse();

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

Dismiss Bootstrap by clicking anywhere

I have a specific input that is displayed when clicked and disappears with the next click: <a href="#;" class="asset_info" data-asset_id="{{ asset.pk }}" data-toggle="focus" tabindex="0" data-placement="left" data-trigger="focus" >Hello</a> ...

Successful Mongoose query in Node.js, however the array remains empty even after using forEach loop. Issue with MongoDB integration

After performing a forEach inside an asynchronous method, I am trying to return an array of names. The issue is that despite the forEach working correctly, the array always ends up empty. On the website side, here is my request: function retrieveCharity( ...

Implementing conditional statements using jQuery for multiple selections

Having two unique IDs, I am planning to set a condition that corresponds with my query. $("#foo", "#bar").foo.bar({ baz: function() { if(selector == "#foo") { console.log("foo"); } else { console.log("bar"); } } }); ...

Inexperienced JavaScript user looking for help with handling XMLHttpRequest response data

It's been well over a decade since I last dabbled in JavaScript, so here I am again. My goal is to create a dynamic graph that updates in real time using data from either my backend database or my ESP32 micro-controller. While it's easy to genera ...

Utilizing pointers with character arrays in string manipulation

After spending hours reading, the concept of conversions between { char i ="adf"; char foo[]; char bar[256]; } along with using * and & has left me more confused than ever. I have managed to get some code working. int TX_SEND(char send ...

Is there a way to send a variable to PHP and execute it on the current page?

I need to integrate an inventory search feature on a local clothing store's website. The challenge lies in setting up the PHP script that pulls and organizes the data to run on the same page as the search form itself. Given my limited experience with ...

What steps can I take to stop jQuery's $.getJSON function from converting my AJAX response keys into integers?

I am facing an issue where JQuery is changing the type of keys in a JSON response object from text to integer when populating a select box. This causes the response object to be reordered based on the numeric indexes, disrupting the order of the select box ...

Adding an operation to a function that is linked to an event

On one of my pages, I have a button that triggers some ajax calls with data binding. The binding code is generic and used in various parts of the application, so altering its behavior could impact other users. However, I now have a specific requirement fo ...

Displaying JSON data dynamically by iterating through it in a loop

While working with JSON data in a loop, I noticed that the code quality does not meet my expectations. I have a feeling that I might be missing something in my approach. $(function(){ $.getJSON('data.json', function(data){ let content ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

changing web pages into PDF format

I need to convert HTML to PDF on a Linux system and integrate this functionality into a web application. Can you suggest any tools that are capable of doing this? Are there any other tools I should consider for this task? So far, I have attempted the foll ...

Managing authentication sessions in React

I have been working on a two-part application that combines React, Express, and Apollo for GraphQL. To handle authentication, I have been studying guides and tutorials, and I have made progress by utilizing JWT tokens and the Context API in React: When a ...

Activate PHP using javascript

My PHP script is designed to capture a user's IP address, current webpage, screen resolution, and Date/Time when they visit my website. To implement this tracking functionality on another website, I plan to insert the following line of code: <scr ...

JavaScript error occurring when trying to validate Ajax response

I am attempting to create a report using a dynamically generated form. The form loads successfully through XMLHttpRequest, but the validation for the form fields does not seem to be working. I have experimented with using eval() and found that it only work ...

If you click outside of a Div element, the Div element will close

I am looking for a way to implement a function that will hide a specific div when I click outside of its area. The div is initially set to Position: none and can be made visible using the following function: Div Element: <div id="TopBarBoxInfo1" oncli ...

Angular - the utilization of expressions in view templates

Exploring Angular for the first time and attempting to create a Single Page Application (SPA). I have included the route module, which seems to be functioning properly. However, the templates are not interpreting Angular expressions as expected - for examp ...

How can I leverage the knowledge gained from a class to achieve my desired outcomes?

I'm currently working on a project where I need to read a file and store its contents in an ArrayList. I plan to use the split method from the String class to format the tokens into another ArrayList. However, I'm facing an issue with my while lo ...

Exploring AngularJS $compile and the concept of scoping within JavaScript windows

I've encountered a scoping issue with the use of this inside an angular-ui bootstrap modal. The code below functions perfectly outside of a modal, but encounters problems when run within one: var GlobalVariable = GlobalVariable || {}; (fun ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Step by step guide to verifying email addresses with Selenium WebDriver

A feature in my EXTJS application includes a page with an Email button. When this button is clicked, it generates a link to the page contents and opens the default email client with this link in the body. Upon inspecting the DOM, I found that the Email bu ...