RegEx unable to extract a number ranging from 0 to 23

Can you figure out why this JavaScript regex is having trouble parsing a number between 0 and 23?

pattern = /([0-1]?[0-9]|2[0-3])/
"12".match(pattern) // => matches 12
"23".match(pattern) // => matches 2 (should match 23)

Answer №1

The regular expression retrieves the initial occurrence found. The sequence [0-1]?[0-9] successfully matches 2.

To obtain the desired outcome, it is necessary to rearrange the pattern order:

var pattern = /2[0-3]|[0-1]?[0-9]/;

var pattern = /2[0-3]|[0-1]?[0-9]/;
document.write("12".match(pattern));
document.write('<br/>');
document.write("23".match(pattern));

UPDATE

The mentioned code will match 234 and return 23. To avoid this match, you can utilize word boundary \b, or include ^, $ anchors as suggested by Gergo Erdosi:

var pattern = /\b2[0-3]\b|\b[0-1]?[0-9]\b/;

var pattern = /\b(2[0-3]|[0-1]?[0-9])\b/;

Answer №2

What could be the reason for the failure of this javascript regex in extracting numbers ranging from 0 to 23?

The reason behind the failure is that the first pattern in your regex always aims to match the input string before encountering the "|". Once a match is found, it will not proceed to the next pattern after the "|". In this case, your initial pattern matches "2", causing it to stop at that point.

To address this issue, consider reversing the order of the patterns or using start and end anchors to validate the input string more effectively.

> var pattern = /^([0-1]?[0-9]|2[0-3])$/g;
undefined
> "12".match(pattern)
[ '12' ]
> "23".match(pattern)
[ '23' ]

Answer №3

Ensure that the regular expression aligns with the entire string:

pattern = /^([0-1]?[0-9]|2[0-3])$/

Answer №4

Almost there! Consider trying the following approach:

pattern = /^([0-1]?[0-9]|2[0-3])$/

Currently, your regex is only capturing part of the input before moving on to evaluate the second half. To ensure a complete match, consider adjusting your expression accordingly.

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

storage location for data in JSON format

When using content type : "application/x-www-form-urlencoded", the result is stored in Request.Form in Asp MVC. However, for "application/json", the storage location cannot be found. Below is the code that is being used: AJAX part // reading form da ...

Printing feature not functioning properly on Internet Explorer version 11

Currently, I am facing an issue with printing a document using a blob URL and iFrame. Everything works perfectly in Chrome, but unfortunately, it's not functioning properly in IE browser. I need guidance on how to successfully print a blob URL that i ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Encountering a problem during the creation of a fresh Angular 2 project

After installing AngularJs with the command npm install -g angular-cli, I encountered an error when trying to create a new project: Cannot find module 'reflect-metadata' How can I resolve this error? ...

Utilizing JSX within this.state results in it being displayed as plain text when rendered

Currently, I am dynamically rendering a list of elements and I need to insert other elements in front of them based on key-value pairs. I want to utilize <sup></sup> tags for these elements, but they are appearing as plain text rather than sup ...

I am facing an issue where my Popover functions correctly when elements are added using HTML, but not when they are dynamically created

I'm currently working on a method to incorporate multiple popovers that have a similar appearance to the following: The screenshot of my first JsFiddle project (click to view) The initial progress I've made can be seen in my first JsFiddle, acc ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

Having trouble implementing the page object model with cucumber.js: bug detected!

I have been working on implementing a page object pattern in my cucumber.js test automation suite with selenium webdriver. However, I am facing an error when trying to call the page object from my test step. The folder structure I am using is as follows: ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

Issues with Weglot link hooks not functioning properly within the sticky header

I have integrated Weglot for translations on my website, aigle.ca. Due to issues with their widget, I am using link hooks instead. You can find more information about link hooks at: weglot.com link-hooks However, when scrolling down the page and the menu ...

The issue arises when trying to use jQuery on multiple elements with the same class

Recently, I came across a jQuery script for my mobile menu that changes the class on click event. jQuery("#slide-out-open").click(function() { if( jQuery( this ).hasClass( "slide-out-open" ) ) { jQuery('#wrapper').css({overflow:"hidd ...

Tracking the latency of WebSockets communications

We are in the process of developing a web application that is highly responsive to latency and utilizes websockets (or a Flash fallback) for message transmission to the server. While there is a fantastic tool known as Yahoo Boomerang for measuring bandwidt ...

Retrieving an Instance of Google Maps Object with the Help of JQuery

I'm currently working on a script that, when executed, will retrieve an instance of a Google Maps object from the webpage using JQuery. For example, if there is a map present on the page, it will be structured like this: <div class="map">....& ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

Bootstrap 5 does not support tab navigation functionality

I created a new HTML page, and I encountered an issue while trying to enable tabs using JavaScript. <html> <head> <title>Excel Viewer</title> <link hr ...

Retrieve JSON object from dropdown menu

I need to retrieve the object name from a dropdown menu when an item is selected. How can I access the object from the event itemSelect? Thank you for your attention. View Dropdown Menu XML code: <core:FragmentDefinition xmlns="sap.m" xmlns:c ...

Why is my react-hook-form sending an array with no data when making an axios request?

Within a container, I have mui Chips that contain labels. The objective is to utilize these chips as selectors, using onClick to add the label values to a list that will be sent in an Axios request. This needs to be achieved without the use of a textfield, ...

Gather and consolidate all files into a single file using Node.js / JavaScript

I currently have 3 JSON files located in my project/Folder file1.json { "id":"01", "name":"abc", "subject":[ "subject1":"Maths", "subject2":"Science" ...

What is the Best Way to Ask Users Not to Delete Local Storage Information?

As I work on developing an application using angularJS, the need to save data locally has arisen. To achieve this, I am utilizing HTML5 local storage. One challenge faced with HTML5 local storage is that when a user clears their browsing data, all stored ...

retrieve information from the local JSON file

Hi there, I am looking to retrieve data from my JSON file and then display it in HTML. Before that, I want to simply log it in the console. How can I accomplish this task? The JSON file will be updated based on user input. varer.json [{"id":&qu ...