Converting a string into an array with varying lengths using regular expressions

Transforming a string into an array with a length of 2 can be achieved using the following method.

let str1 = '112213';
let str1Array = str1.match(/.{2}/g);
console.log(str1Array);

The output will be

[ '11', '22', '13' ]

Now, is it possible to obtain [ '1', '12', '2', '13'] in a similar way?

Answer №1

Consider using the split() method instead of match(), allowing for both lengths to be provided in a single regex pattern:

(.)(..)?

The optional quantifier is important when the string length is not even.

Here's an example of JavaScript code that implements this approach:

console.log(
  '112213'.split(/(.)(..)?/).filter(Boolean)
);

Answer №2

function myCustomFunction() {
  var userInput = document.getElementById("input").value;
  console.clear()
  var regex = /(.)(.{2})/g;
  var match;
  var resultArray = [];
  
  do {
      match = regex.exec(userInput);
      if (match) {
          resultArray.push(match[1], match[2]);
      }
  } while (match);
  console.log(resultArray)
}
<form action="javascript:myCustomFunction()">
  <input id="input" type="text" value="112213"><br><br>
  <input type="submit" value="Submit">
</form>

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

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

Does __ only function with curried functions as intended? What is the reason for it working in this case?

I'm trying to figure out the reason behind the successful usage of __ in this particular code snippet : function editAddress (id, addressId, model) { return BusinessService .getById(id) .then(unless( () => checkUrlValue(add ...

Is it possible to establish a components route without importing withRouter in the file?

I am aiming to initiate a state modification upon receiving endpoint data so as to synchronize my GUI. The designated file for handling incoming socket data is referred to as sockets.js. Inside sockets.js, my goal is to trigger a route transition. if (da ...

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

Obtain every selection from the multiselect box and add them to the database

How do I assign all selected measures to my "answers" object? The selected measures are: get selectedMeasures() { const items = this.measureItems.filter((item: any) => item.selected); return items.length ? JSON.stringify(items.map(item => ...

BufferGeometry-based Three.js mesh fails to display

Currently, I am in the process of developing a WebGL game using Three.js. In order to enhance performance, I have made the decision to transition from using THREE.Geometry to utilizing THREE.BufferGeometry. However, after making this change, I encountered ...

Executing JavaScript code only if certain date conditions are satisfied

I'm trying to come up with a way to execute a piece of JavaScript code when a specific date condition is met: For instance: Do not run the code if the date falls between June 6th, 2014 5PM CST and June 16th, 2014 5PM CST. Or maybe the opposite wou ...

Tips for adjusting the position of an object when resizing the window

The problem at hand is as follows: Upon refreshing the page, my object is initially positioned correctly. However, resizing the window causes the object to resize and reposition correctly. But, if I refresh the page after resizing the window, the object i ...

Tips on extracting and displaying data from a JSON response in JavaScript to HTML

Hello! I'm new to JavaScript and I have a question regarding AJAX requests. I've successfully received a JSON response and I want to dynamically append specific data from this response to HTML fields. Below is an example of the JSON response tha ...

In Reactjs, you can prevent users from selecting future dates and times by modifying the KeyboardDateTimePicker component

I am currently using the Material UI KeyboardDateTimePicker component and have successfully disabled future dates with the disabledFuture parameter. However, I am now looking for a way to disable future times as well. Any suggestions or solutions would b ...

Can one initiate a server within Zapier Code?

Is there a way to send an HTTP CODE = 200 with a response body of 'OK' when receiving a notification on Zapier? I attempted to use the following code snippet in Zapier: var http = require('http'); const server = http.createServer((r ...

Having difficulty entering text in the modal text box and updating it with a new state

Within my render method, I am utilizing the following model: { showEditModal && <Modal toggleModal={this.togglePageModal} pageModal={true}> <h2 style={{ textAlign: "center", width: "100%" }}> ...

Maintain the highlighted background of the selected slot in react-big-calendar even after the selection process is completed

Currently, the default behavior is that when a slot is selected, it is highlighted in gray. However, once the selection is stopped, the highlighting disappears from the calendar fields. If we were to open a modal upon selection, this may not be necessary. ...

What are the steps to clear a client's local cache after updating my website?

Is there a simple way to clear the cache of all players who have previously played my game? The game stats are stored in local storage, and some players experienced bugs when the stats were incorrect. This outdated data is now affecting the updated stats ...

Concealing Angular Flexslider until it is entirely loaded

I'm having trouble getting my angular flexslider to display images smoothly. Currently, the images take a moment to load and it doesn't look great. I'd like them to fade in once everything is fully loaded. How can I achieve this? I've t ...

Generate random floating numbers at intervals and calculate their sum

I've been given a task to complete. Upon page load, there should be 10 fields labeled as A, B, C, D ... each with the initial value of 3. After the page has loaded, every 2 seconds all field values should change randomly. The change will be a rand ...

Utilize Express to update user data stored in MongoDB

Greetings everyone! I've been attempting to develop an update function for my app, but unfortunately, I encountered an error that states getState is not a function. (In 'getState()','getState' is 'Stephanson'), which refe ...

Setting attributes for elements in NativeScript/Angular can be accomplished by utilizing item properties

Is it possible to call a function on an item element inside an ngFor loop in order to set some properties? Otherwise, I find myself having to loop twice - once in the script and then again in the template - setting temporary properties to a model that shou ...

Troubleshooting HTTP Issues in Angular 2

I am currently facing an issue with my Angular 2 project's Http functionality. I have defined it as a parameter in the constructor, but it keeps printing as undefined. Below is the snippet of code from my project: import 'rxjs/add/operator/toPro ...

How to disable map zoom controls in react-leaflet

Currently, I am developing a react-leaflet application project and facing an issue with separating the zoom control from the map itself. This is a similar concern that was addressed in a vanilla Leaflet context on this link. Now, I am attempting to achieve ...