Using Javascript Regex to divide a string into an array of adjacent characters

I've been attempting to achieve a similar task as someone else, who accomplished it using Ruby while I'm striving to do so with Javascript:

Split a string into an array based on runs of contiguous characters

The objective is to split a single string of characters into an array of contiguous characters. For instance:

Given the input string:

'aaaabbbbczzxxxhhnnppp'

It should result in an array like this:

['aaaa', 'bbbb', 'c', 'zz', 'xxx', 'hh', 'nn', 'ppp']

My current attempt looks something like:

    var matches = 'aaaabbbbczzxxxhhnnppp'.split(/((.)\2*)/g);
    for (var i = 1; i+3 <= matches.length; i += 3) {
        alert(matches[i]);
    }

Although it somewhat works, there are still inaccuracies. I find myself splitting too much and having to manipulate the index to filter out unwanted entries.

How can I obtain a clean array with only the desired content?

Appreciate your help!

Answer №1

Don't worry, your regex is correct. You simply need to use the appropriate function. Instead of String.split, make sure to use String.match:

var matches = 'aaaabbbbczzxxxhhnnppp'.match(/((.)\2*)/g);

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

The basic Kendo UI remote DataSource fails to fetch any data

I'm working on a basic exercise where my DataSource object is not returning any data. Here's a snippet of the code: var data = new kendo.data.DataSource({ transport: { read: { url: "data.json", ...

Utilize HTTPS and HTTP with Express framework in node.js

Currently, I am utilizing the express (3.0) framework on node.js to handle routing in my application. While most of the application makes use of the http protocol, there is a specific route that I intend to serve exclusively via https. This particular par ...

The Three.js IEWebGL Plugin

After developing a code that successfully rotates a cube with trackball using the three.js library and webgl, I encountered compatibility issues when trying to run it on Internet Explorer 10. Despite downloading IeWebgl to assist in making it run on IE10 ...

How can a JavaScript code be used to navigate to a different HTML file within the same directory that is stored within a folder?

Here is the sample HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewpor ...

Effortless glide while dragging sliders with JavaScript

In the code below, an Object is looped through to display the object key in HTML as a sliding bar. jQuery(function($) { $('#threshold').change(updateThreshold); function updateThreshold () { var thresholdIndex = parseInt($(&apos ...

Tips for creating a login/registration system in a single page application

I've been working on a single-page application with ngRoute for navigation between tabs. Now, I need to incorporate a login and registration feature. After that, users should be able to access all the tabs. I'm unsure about the following: 1) Sho ...

Utilize an array value as a parameter for getStaticProps within Next.js

Currently, I am fetching my Youtube playlist using a fetch request and utilizing getStaticProps(). However, I am encountering an issue where my playlist is dependent on the result of an array of objects. export async function getStaticProps(){ const MY_P ...

Getting the start of a day for a specific date in JavaScript while considering the timezone

I'm having trouble determining the start of a day while factoring in timezones using javascript. Consider this example: var raw_time = new Date(this.created_at); var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms); // Th ...

Checking the validity of an input element with jQuery: How to determine if the valid or invalid pseudo-class has been applied?

Is there a way to check for the application of the CSS3 :valid or :invalid pseudo-class on an input element using jQuery? I want to verify if the form element has passed CSS validation before allowing the submit button to be enabled. Here are some methods ...

Modifying the appearance of an element's style attribute with Selenium and Java

When using Selenium in Java, I am encountering issues changing the style within a specific div section. The goal is to modify the style of the div element with the id of "navbar". Please refer to the provided image for clarification. Here is a brief snipp ...

Disregard any labels when it comes to clickable areas for mouse events

Here is a simple example in JSFiddle where a text is displayed over an image inside a div element. Depending on where the cursor hovers, it can exhibit three different behaviors: pointing hand over the image, allowing text selection over the content of the ...

Stop the Bootstrap 5 accordion from expanding when the spacebar is pressed in the header text input

Within my React app using react-bootstrap, I have implemented an accordion component that expands or collapses based on the user's interaction with a text input located in the AccordianHeader component. Interestingly, whenever the spacebar is released ...

Begin by checking off all checkboxes

My HTML page includes jQuery code that allows me to set all checkboxes to a 'checked' state when clicking on a 'check all' checkbox. However, I want to have all checkboxes checked by default when the page loads, without needing to click ...

What is the best way to determine the index of the area that was clicked on in chartjs?

I am currently working with a chart that may not have elements at specific indices, but I am interested in determining the index of the area clicked. https://i.sstatic.net/rEMbG.jpg When hovering over an area without an element, the assigned tooltip is d ...

Implementing React routing with AntD's horizontal menu: a step-by-step guide

I have the main layout component displayed below. I am looking to enable navigation to the home, holiday calendar, and event pages when a menu item is clicked. How can I achieve this functionality with the horizontal menu provided in the code? The main l ...

Can a single-page application be created using Express without utilizing React, Angular, or similar frameworks?

Our codebase is currently exclusively built on express, and we are looking to expand it while transitioning into a single page application. At this point in time, I am hesitant to rework the code using frameworks such as Angular or React to achieve this go ...

Identifying the index of form inputs and select elements in JavaScript

In my HTML form, I have a mix of inputs and selects that are combined together: <th><input type="text" id="bGroup" name="search_group" /></th> <th><input type="text" id="bEvent" name="search_event" /></th> <th> ...

Utilize the power of JavaScript to recursively map object keys

I am working with an array of objects that have varying depths. My goal is to output the names in a specific format: Top Level Top Level > Sub 1 Top Level > Sub 1 > Sub 1-2 Top Level > Sub 2 Unfortunately, I am only able to get the name of th ...

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

The functionality of the activePost is being disrupted by the useState hook when the useEffect is activated by the

My objective was to retrieve posts from Graphcms, store them in an array called 'posts', and display them in a postlist. Then, based on the user's selection from the postlist, the main component would update accordingly. Although I successfu ...