The use of the g flag with String.match still only retrieves the initial match

I'm currently attempting to tackle a challenging binary gap issue using regex, but I've hit a roadblock with it.

If I use the following code snippet:

Number(101001000).toString().match(/(1[0]+1)/g)

It only returns ["101"], whereas I was hoping for

["101", "1001"]
.

Could there be an error in my approach or is achieving this outcome solely through regex not feasible?

Answer №1

function findBinaryGaps(binaryStr) {
  return (
    binaryStr
    .split("1")
    .reduce((accumulator, currentValue, index, array) => {
      if(index && index < array.length-1)
        accumulator.push(1 + currentValue + 1);
      return accumulator;
    }, [])
  );
}

console.log(findBinaryGaps(Number(101001000).toString()));
console.log(findBinaryGaps("00101001000"));
console.log(findBinaryGaps("001010011000"));

Answer №2

To achieve this using only regex, it's important not to include the terminating 1 in the match result, as it might be needed for a subsequent match.

Instead, ensure that there is a 1 immediately following the match without capturing it.

If you want to retain the ending 1 in the output, adjust the match result accordingly:

console.log(
   (101001000).toString().match(/10+(?=1)/g).map(m => m + "1")
)

Some additional points to consider:

  • It is unnecessary to use the Number function since 101001000 is already a number. The extra step is mainly needed to clarify the dot in .toString(). Simply adding parentheses resolves the ambiguity. Another option is to add an extra dot: 101001000..toString() will also work.

  • Square brackets are not required around 0 in your regex, nor do you need to enclose the entire expression in parentheses.

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

Executing an Ajax SPARQL request in Firefox

I've been attempting to run an asynchronous Ajax sparql query on dbpedia using Firefox, but I encountered a strange issue that I can't seem to figure out. Surprisingly, the query works perfectly fine in Chrome, Edge, and Internet Explorer, but wh ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

What is causing the "mb-3" class from Tailwindcss to malfunction with next/link?

The "mb-3" class from Tailwindcss in this Next.js component seems to have no effect in the Y direction. However, when using the "m-3" class, it also doesn't affect the Y direction, but instead has an impact on the X direction. impo ...

The parseJSON function is not compatible with AJAX requests

I am attempting to use ajax and retrieve JSON data in WordPress. Here is my Ajax code: $.ajax({ type: "POST", dataType : 'html', url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php", da ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

Ways to transfer ID to a different HTML page

I have some Javascript code in a file named nextPage.js. When this code is executed by clicking on something, it should transfer the value of category_id to another page called reportlist.html. Can you please provide assistance with this? var base_url = " ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

What is the best way to combine JavaScript objects with identical values?

We have a task to compare each input key with others to find any common values. If there are common values, we need to concatenate them together and display the pairs. If no common values are found, then an empty array should be displayed as output. inpu ...

Is it possible to bundle Live using Angular 2 and SystemJS-builder, even when attempting to load modules from node_modules?

I'm having a bit of trouble transitioning my angular 2 application into production. It seems to be searching for scripts within the node_modules directory. I'm fairly new to angular 2 and despite spending half a day looking for a solution, I can ...

A guide to specifying the Key-Callback pair types in Typescript

Here is an object containing Key-Callback pairs: const entitiesUIEvents = { newEntityButtonClick: () => { history.push("/entity-management/entities/new"); }, openEditEntityDialog: (id) => { history.push(`/entity-mana ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

``Are you looking to create multiple canvases in a loop?

I've managed to get this command working exactly as I wanted: http://jsfiddle.net/m1erickson/64BHx/ However, I didn't anticipate how challenging it would be to turn the drawing into reality here: What I attempted to do is illustrated in this li ...

Issue of flickering/flashing in Next js when using conditional rendering

I've been attempting to implement localstorage for storing authentication with Next.js. I am using conditional rendering to ensure that localstorage is accessible before displaying the content. However, I am facing an issue where the page flickers or ...

Harnessing the power of jQuery to create a horizontal scrolling experience based

I'm working on creating a javascript version of the website that currently uses flash. So far, I have completed the basic layout, which consists of a simple horizontal container with divs. You can view the code here http://pastebin.com/U3z2aJve I a ...

The issue arises when AngularJS binding to a JSON object results in the value being

I am encountering a complex problem with nested bindings in custom directives. The JSON structure I am working with resembles the following; { survey: questions:[ { text:'Question 1', answers:[ { ...

Activate the drop-down menu in Angular 6 by hovering over it with your mouse

I am just beginning my journey with Angular 6 and Bootstrap. Currently, I am working on a Navigation bar that consists of 3 navigation items. One of the nav items is called "Store", and when a user hovers their mouse over it, I want to display a mega menu ...

Utilizing the output from a console.log in a webpage

Although the function I created is functioning properly and successfully outputs the value to my terminal onSubmit, I am facing difficulty in understanding why this code isn't updating my html. router.post('/index', function(req, res, next) ...

What is the process for a browser to load JavaScript resources?

I decided to do some research on how browsers load resources like CSS, JS, Images, HTML, etc. After creating a prototype code based on my findings, I became a bit confused during testing. Below is the Plnkr code where I included a <script> tag to int ...

Adding JavaScript to dynamically loaded AJAX content

I'm new to AJAX and JavaScript and unsure of how to get it working. Here is the website: When you click on portfolio images, the details load via AJAX. I want to create a slideshow for projects with multiple full-sized images. However, due to the co ...

Table Header Stays Put Without Shrinking or Expanding with Window Adjustment

I have a sticky table header that stays at the top when scrolling down on my web page. To achieve this effect, I followed the solution provided on css-tricks.com/persistent-headers/. However, I encountered an issue where the sticky table header does not ...