Separate a string into individual parts while also including the separators as their own values within

Looking for help with extracting numbers and operators from basic math equations. Is there a way to split each number into an array while keeping the operator separate?

"123/12*312+4-2"

The desired output is as follows:

["123", "/", "12", "*", "312", "+", "4", "-", "2"]

I have tried using this code:

str.split(/[^\d]/)

Other methods I've attempted end up keeping the separator attached to the numbers instead of separating them.

Answer №1

To extract specific parts using regular expressions, utilize a capture group:

let text = "123/12*312+4-2";
let array = text.split(/(\D)/);

console.log(array)

\D serves the same purpose as [^\d] (represents anything other than digits)

Answer №2

To solve this problem, utilize the String#match method.

console.log(
  "567/45*678-9+1".match(/\d+|\D/g)
)

In regular expressions, use \d+ to identify number combinations and \D for non-digits.

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

implementing key strokes instead of buttons in django forms

I am currently working on a website where users can enter text, vote on entries, and view live tables of the most popular submissions. You can check out the site here: This project is coded using django. I have successfully implemented a text entry form a ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

Replacing a string in a textarea using Jquery

Trying to dynamically replace a string value in a textarea while typing into a textbox using jQuery. Utilizing the keypress event for this functionality. Any ideas on what could be causing issues with this example? <input type="text" id="textbox" /> ...

ReactTable version 7 is experiencing an issue where the noDataText is not displaying when there is empty data, specifically when using

I'm currently working on showcasing specific data using react table v7. It's functioning flawlessly with the useTable hook, however, it only shows an empty table without the expected noDataText. import React, { useContext, useEffect, useMemo } fr ...

An error has been caught in the Angular JS application while using the highcharts-ng module: [$injector:modulerr]

I'm encountering an issue while trying to integrate Highcharts into my Angular/Node/Express application. I am utilizing the highcharts-ng directive available at https://github.com/pablojim/highcharts-ng Every time I run my app, I consistently receive ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Use JavaScript to load a component or call a method only when it is necessary

Looking for a solution to eliminate script tags from my HTML views. For instance: (A view containing a script tag) <script type="text/javascript"> $jQuery().ready(function() { call.a.method(); } </script> I want to remove th ...

Angular7 is throwing an error saying it cannot read the property 'post' of undefined

Looking to create a custom validation in Angular 7. Here is the code snippet: CheckUserNameExisit(control: AbstractControl): { [key: string]: any } { console.log('in functions') return new Promise(resolve => { let httpClient: HttpClient ...

Tips for sharing a global variable in Node.js multi-cluster mode while running Socket.IO on an NGINX load balancer but using fork mode with PM2

My socket.io app is currently running with NGINX load balancing on 6 cores, distributing the load among them. When I use pm2 list myapp, it shows that the app is running in fork mode but spanning across 6 processes due to NGINX load balancing. │ myapp-1 ...

Can you explain why there is a discrepancy in the canvas coloration?

When I try to draw a line on my canvas with color "#ca5100", the actual color that appears is "#e4a77f". Why does this difference occur and how can I ensure that the correct color is set? var ctx = document.getElementById("mycanva").getContext("2d"); ct ...

Enhancements in Converting JSON Objects to HTML Lists Using jQuery

I have created a function that converts a multi-dimensional JSON object into an HTML list. You can check it out here: http://jsfiddle.net/KcvG6/ Why is the function rendering the lists twice? Update: http://jsfiddle.net/KcvG6/2/ Are there any impro ...

How to retrieve the index of a nested ng-repeat within another ng-repeat loop

On my page, there is an array containing nested arrays that are being displayed using ng-repeat twice. <div ng-repeat="chapter in chapters"> <div ng-repeat="page in chapter.pages"> <p>Title: {{page.title}}</p> </d ...

Why does my Javascript cross-domain web request keep failing with a Status=0 error code?

UPDATE: I've been informed that this method doesn't work because craigslist doesn't have an Allow-Cross-Domain header set. Fair point. Is there an alternative way to download a page cross-domain using Javascript in Firefox? It's worth ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

Creating custom project structures with Sails.js 0.10 generators

When looking at the upcoming Sails.js 0.10 release, one exciting feature that stands out is the addition of custom generators (currently @ rc4). You can find a migration guide on Sails' GitHub page highlighting the benefits of these generators, but i ...

Is there a quicker way to reference the same post on jQuery?

I am looking to automatically start the same ajax request once it finishes. The reason behind this is that using setInterval does not guarantee that all requests made in the first second will be completed before the second setInterval call. I have explore ...

Strategies for Structuring Django and JavaScript Codebases

I'm grappling with the best way to structure my javascript and django code. Previously, I would include my page-specific javascript directly in the template file within a <script> tag. However, as my javascript code grew, this approach led to a ...

What is the best way to collapse an array within an object?

I'm looking for a way to flatten an array within an object using JavaScript, preferably ES6. I'm not sure if "flattening" is the correct term here, but I just want a solution to achieve this transformation. Currently, I have this structure: { ...

Exploring the power of Jade and Angular through implementing a for loop within a table structure

I'm brand new to using Jade and Angular, and I could really use a hint from someone more experienced. ... - for (var i = 0; i < p.length; i++) tr td= i + 1 td= price(value='p[i].somedbstuff') ... I want the la ...