Ways to separate a string based on changing values in Javascript

Given this unmodifiable string:

"AAACCDEEB"

I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so:

[['A','A','A'], ['C','C'], ['D'],['E','E'], ['B']]

Answer №1

you might want to give this a shot

"AAACCDEEB".match(/(.)\1*/g) 

You'll get results like ["AAA", "CC", "D", "EE", "B"]

This code uses a regular expression pattern to match any character repeated 0 or more times, making it quite versatile.

If you're interested in learning more about regular expressions, there are plenty of resources available - they can be very handy in situations like these!

If my solution works for you, feel free to accept it as the answer :)

Answer №2

Perhaps a different approach would look something like this:

 var str = "AAACCDEEB";
 var strArray = [[], [], [], [], []];
for(var x = 0; x <= (str.length-1); x++){
var val1 = 'A';
var val2 = 'C';
var val3 = 'D';
var val4 = 'E'
var val5 = 'B';
for(var n = 0; str[x] == val1; n++){
strArray[0][n] = str[x];
}
for(var m = 0; str[x] == val2; m++){
strArray[1][m] = str[x];
}
for(var o = 0; str[x] == val3; o++){
strArray[2][o] = str[x];
}
for(var z = 0; str[x] == val4; z++){
strArray[3][z] = str[x];
}
for(var i = 0; str[x] == val5; i++){
strArray[4][i] = str[x];
}

}
document.write(strArray);

If you find this helpful, please let me know by accepting it!!

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

Modifying information in a single array in Vue JS has a ripple effect on

I'm really struggling to understand what the ... want with this Vue component! Can someone please help me out? Here is my code: var groupadding = new Vue({ el: '#groupAdd', data:{ currentFullData: [], localData: [] }, method ...

How can I enhance this conversion function from an Array to an Object in JavaScript?

Looking to construct an object consisting of empty arrays using values as keys. const CATEGORIES = ['apple', 'banana', 'orange'] generateCategoryObject() === { apple: [], banana: [], orange: []} function generateCategoryO ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

The express post request body fails to appear, rendering it empty

Server Side Code const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true })); app.post('/',(req,res)=>{ console.log(req.body) }) Client Side Code const da ...

Is it feasible to relocate an embedded swf file from one tag to another?

My HTML contains two containers for embedded swf files: <div id="player1"></div> <div id="player2"></div> If I load an embedded video into the first div (player1) like this: swfobject.embedSWF("someURL","player1"); Is it possibl ...

How to Make Buttons Vanish and Reappear

Check out this fiddle for a picture button 'scroller' that I created. It may not be perfect, but my main focus is on making the arrow buttons fade in and out when reaching the end of the picture order. I am considering using a JavaScript functio ...

Enhance React scrollbar functionality without relying on third-party dependencies

Currently working on enhancing the appearance of the scrollbar within my ReactJS project. Specifically, I am aiming for a design similar to this example: https://i.stack.imgur.com/2Q0P4.png Experimented with CSS properties like -webkit-scrollbar, -webki ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Creating a service in AngularJS 1.8 with ES6 modules that acts as a bridge to a class based API interface

As I continue to enhance a codebase that originally consisted of a mix of different versions of AngularJs and some unstructured code utilizing various versions of a software API, I encounter an interesting quirk. It appears that this API is accessible thro ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...

Determine the dimensions of Expo's React Native Over the Air (OTA) update

Is there a method to determine the size of the required download for an OTA update before existing deployed apps (e.g. v1) retrieve it following the publication of a new managed Expo app (e.g. v2)? ...

Enhance your message inbox experience with jQuery/Javascript features inspired by Gmail, including the ability to select all messages with a checkbox and

It is truly satisfying to be here working on developing a private message inbox for my website, especially after successfully implementing a complete user signup/login and activation system. A few months ago, I never believed I had enough patience to grasp ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

"Unlocking the door: a step-by-step guide to logging in with ajax and json for your hybrid

As a beginner coder, I am currently working on a project to create a mobile web login form using json and ajax. To test my code, I followed the tutorial provided here. This is the code I have developed: <!DOCTYPE html> <html> <head> ...