Break down a string in Javascript into segments of a certain length and save them in a variable

Is there a way to split a JavaScript string into an array of strings of a specified length, where the length can vary? I need to have the length parameter as a separate variable:

var length = 3;
var string = 'aaabbbcccddd';
var myArray = string.match(new RegExp('.{' + length + '}', 'g'));

How can I use the length variable in the match function? Or is there any other solution similar to str_split in PHP?

My question is different from: Split large string in n-size chunks in JavaScript because I already know how to slice, but I want to know how to use a variable in the match function.

I am struggling to achieve this, as mentioned inJavascript Regex: How to put a variable inside a regular expression?

Answer №1

Using string.substr() is a more efficient option when you need to split by length only.

For those who are interested in using regex to achieve the same result, you can define a variable in your RegExp as shown below.

var length = 3;
let reg = new RegExp(`(.{${length}})`, 'g')
var string = 'aaabbbcccddd';
var myArray = string.match(reg);
console.log(myArray);

Answer №2

I'm not sure if you managed to find a solution to the issue:

I saw your question yesterday, but I couldn't respond because it was on hold or marked as a duplicate. However, I later found a solution. Hopefully, it helps if you haven't fixed it yet.

What worked for me was using new RegExp(). Here's an example in a fiddle:

var length = 3;
var string = 'aaabbbcccddd';
dynamicRegExp = new RegExp("(.{"+length+"})", "g");
console.log("Regex used: "+ dynamicRegExp);
var myArray = string.match(dynamicRegExp);
console.log("Output: "+ myArray);

Syntax

new RegExp(pattern[, flags])
RegExp(pattern[, flags])

Parameters

  • Pattern

The text of the regular expression or, as of ES5, another RegExp object (or literal) to copy (the latter for the two RegExp constructor notations only).

  • flags

If specified, flags indicates the flags to add, or if an object is supplied for the pattern, the flags value will replace any of that object's flags (and lastIndex will be reset to 0) (as of ES2015). If flags is not specified and a regular expressions object is supplied, that object's flags (and lastIndex value) will be copied over.

What @Code Maniac suggested is also correct and matches my approach.

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

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

Is there a way to create a nested object literal that will return the length of

I am working with JSON data that includes different locations (sucursales) and cars for each location. How can I write a function to calculate the total number of cars across all locations? [{"sucursal": "Quilmes", "direccion&q ...

Disabling a button does not automatically shift the focus to the next element in the tab order

Is there a way to limit the number of times a button can be clicked using jQuery? For example, I want a button that can only be clicked three times before disabling itself automatically. test.html <div class="main"> <input class="one" type="t ...

Explore the Wikipedia API play area by searching based on the user's input

Having trouble searching Wikipedia based on user input. Initially, I suspected a cross-domain issue, but I believe .ajax should resolve that. You can view the codepen here: http://codepen.io/ekilja01/pen/pRerpb Below is my HTML: <script src="https:// ...

Invoking the callback function within the containing scope in Typescript

I am facing an issue with my Angular component where I have a class that includes common services and functions. While passing some functions as callbacks, the scope is getting lost during execution. Let me demonstrate the problem through the code below: @ ...

Deciphering the Regex Riddle: PowerShell's Mighty .NET Regex Power

Context: I currently have a PowerShell script that is designed to handle XML files containing both 'tokens' and 'filters'. The tokens are resolved within the script while the filters are applied to the resolved values of the tokens. T ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

What is the process for incorporating a computed property into an Array<T>?

I currently have the following: var _feedbacks: [feedBack]! My goal is to enhance [feedBack] with an additional property so that I can state: var _ID = _feedBacks.ID My initial attempt was: extension Array { var ID: String { ...

Unable to retrieve props from server-side page to client-side component in a Next.js application router

Currently, I am utilizing app router alongside Next.js version 13.5. Within my /dashboard page (which is a server component), there is an ApiKeyOptions client component embedded. However, when attempting to pass props from the dashboard page to the ApiKeyO ...

Pattern matching for validation

I'm currently experiencing an issue with using regular expressions in Python. The problem lies in the need to search a list and identify strings that contain spaces. Below is the code snippet: def testFunction(self, func): a = re.findall(r&a ...

Tips for preventing directly mutating a prop within a recursive component

The child operates on its own copy of the prop data and can notify the parent using `$emit` when a change occurs. Imagine dealing with a recursive tree structure, like a file system for example: [ { type: 'dir', name: 'music', childr ...

Is there a way to block form submissions for users who have disabled JavaScript?

Our inquiry form mandates users to input basic information such as their name, location, contact details, and a comment or question. Unfortunately, we have been receiving numerous incomplete forms where essential fields are left blank. It has come to our ...

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

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 ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

Utilizing Vue's data variables to effectively link with methods and offer seamless functionality

I am encountering difficulty retrieving values from methods and parsing them to provide. How can I address this issue? methods: { onClickCategory: (value) => { return (this.catId = value); }, }, provide() { return { categor ...