Tips for identifying all five-digit numbers excluding the initial match

I am currently working on a project that involves extracting all 5 digit numbers from a file name, specifically focusing on Employee numbers. The challenge I'm facing is that the first 5 digit number in the file name actually pertains to the job number. Therefore, I need to exclude this initial match and proceed to identify and extract all subsequent 5 digit numbers.

var str = "01_12345_02_02_2019_12347_67890_10112_13141";
var empRegex = /(\d{5})/g;
var empNumbers;
empNumbers = str.match(empRegex).toString();
console.log(empNumbers);

I expect to retrieve "12347, 67890, 10112, 13141" as the output.

However, I am currently getting

"12345, 12347, 67890, 10112, 13141"
but have not been successful in finding a solution that allows me to skip the initial match.

Answer №1

Solution:

Your regular expression contained a typo. It should have been \d{5} instead of d{5}.

Additionally, to remove the first matched element from the array, you simply need to use the shift method. Refer to Array.prototype.shift for more information.

When using the shift method, keep in mind that it modifies the original array and returns the removed element, not a new or modified array. Therefore, make sure to assign the variable to the original array before applying the shift method on it.

To clarify:

(empNumbers = str.match(empRegex)).shift(); 

is correct, whereas:

 empNumbers = str.match(empRegex).shift();

is incorrect as the latter does not retain the changes made by the shift method to the array.

Code Snippet:

var str = "01_12345_02_02_2019_12347_67890_10112_13141";
var empRegex = /(\d{5})/g;
var empNumbers;
(empNumbers = str.match(empRegex)).shift();
console.log(empNumbers);


Alternatively:

Using a Function:

If you anticipate performing this action frequently, it might be beneficial to create a function to handle it. Here's an example of such a function:

var str = "01_12345_02_02_2019_12347_67890_10112_13141", empRegex = /(\d{5})/g;

function matchExceptFirst(str, RE) {
let matches = str.match(RE); 
matches.shift();
return matches;
}

var empnumbers = matchExceptFirst(str, empRegex);
console.log(empnumbers);

Pure Functional Approach:

If you prefer a functional programming style where data is treated as immutable, consider using the filter method of an Array to achieve the same result without mutating the original array:

   let excludeFirstMatch = (str, re) => str.match(re).filter((_,i) => (i));

    var str = "01_12345_02_02_2019_12347_67890_10112_13141", empRegex = /(\d{5})/g;
   
   
   let excludeFirstMatch = (str, re) => str.match(re).filter((_,i) => (i));
    

   console.log( 
   excludeFirstMatch(str, empRegex) 
   );


Edit: Another efficient approach pointed out by @UlysseBN involves using the slice method, which provides a faster solution and also returns a new array.

var str = "01_12345_02_02_2019_12347_67890_10112_13141", empRegex = /(\d{5})/g;
   
   
   let excludeFirstMatch = (str, re, len = str.length) => str.match(re).slice(1, len);
    

   console.log( 
   excludeFirstMatch(str, empRegex) 
   );

Answer №2

How can I find all 5 digit numbers except the first one?

An example solution is as follows:

var str = "01_12345_02_02_2019_12347_67890_10112_13141";
var numRegex = /(?:^.*?\d{5}.*?)?(\d{5})/g;
var numbers = [];
var item;

while (item = numRegex.exec( str ))
    numbers.push(item[1]);

// ---------Output-----------
console.log(numbers);

Answer №3

Here is an example of using the shift() method:

 

var str = "01_12345_02_02_2019_12347_67890_10112_13141";
var empRegex = /(\d{5})/g;
var empNumbers = str.match(empRegex);
empNumbers.shift();
empNumbers = empNumbers.toString();
console.log(empNumbers);

Answer №4

If you want to extract specific elements after a regex match, you can utilize array.slice:

var str = "01_12345_02_02_2019_12347_67890_10112_13141";
var empRegex = /(\d{5})/g;
var empNumbers;
empNumbers = str.match(empRegex).slice(1).toString();
//                              ---------
console.log(empNumbers);


An alternative method, assuming the format of the string remains constant, is to avoid using regular expressions altogether:

var str = "01_12345_02_02_2019_12347_67890_10112_13141";
var empNumbers = str.split('_').slice(-4).toString();
console.log(empNumbers);

Some people, when faced with a problem, think "I'll use regular expressions." Now they have two problems.

Check out Coding Horror's blog for more insights.

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

Issue: Angular controller fails to load during testing with Poltergeist/CapybaraExplanation: While conducting

Exploring the world of rails/angular for the first time has been an interesting journey. Currently, I am focusing on testing angular with poltergeist/capybara. While everything runs smoothly in the actual browser, it appears lifeless during testing. Despit ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

Changing URI to File Object using JavaScript

I have successfully retrieved the URI of a selected file in my Ionic app using the cordova-fileChooser plugin. https://i.sstatic.net/NxXti.jpg Next, I used the cordova-plugin-filepath to obtain the absolute path of the file from the nativeURL on the phon ...

Initialize: Establish the views directory on a distant server

Is there a way to specify the views folder located on another shared machine? While I can access files on a remote machine through Windows Explorer using \\0.0.0.0\myfolder, setting the views folder to a location on a different remote machin ...

The event listener for the hardware back button in $ionicPlatform is being triggered repeatedly

Encountering a glitch with the back button being triggered multiple times. While I'm in the "messages" $state, everything functions normally when hitting the back button. var messageIsClosed = true; $ionicPlatform.onHardwareBackButton(function(even ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

How jQuery manipulates the DOM during a drag-and-drop operation

My current challenge involves implementing jquery-ui sortable on items that appear while scrolling. Below is the code snippet I am using: var gridTop = 0, gridBottom = container.outerHeight(); $('#play-list').on('scroll', ...

Using TypeScript to target elements in a React component with getElement

When incorporating this functionality in Pure React const Fleet = () => { const closeSidebar = () => { document.getElementById("mysideMenu").style.width = '0'; document.getElementById("pg-content").style.marginLeft = & ...

You can utilize the Toggle Button to alternate between multiple classes, not just two

Currently, I am learning Java with Spring Boot and Thymeleaf. While creating some views, I faced a challenge. Initially, I wanted to create a toggle button for "Pending" and "Received". However, now I am attempting to add the option "Cancelled", but I have ...

Having trouble properly refreshing Bootstrap scrollspy that is spying on the <body> element

I've been looking at a post on Bootstrap's scrollspy component (found here). In my code, I initialize a new scrollspy to track the body element using: $("body").scrollspy({ offset: 25 }); As my code progresses, I make AJAX requests that add or ...

The issue with Extjs store.proxy.extraParams being undefined appears to only occur in Internet Explorer

I currently have an ExtJs store set up with specific configurations. var fieldsStore = new Ext.create('Ext.data.Store', { model : 'FieldsModel', proxy : { type : 'ajax', url : 'queryBuilder_getQueryDetails', ...

Tips for inserting values into an array in NodeJS

Hello there! I am currently in the process of learning Node and experimenting with some interesting things using JavaScript and Node.js. However, I have hit a roadblock while trying to combine separate "where" statements in Sequelize into one cohesive stat ...

"Utilize Ajax to load PHP content and dynamically refresh a specific div

I have implemented an image uploading system, but now I want to incorporate a feature that allows users to rotate the uploaded images using Ajax. The challenge I'm facing is that if the session variable is lost during a full page update, I need to ens ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Having trouble with the Ajax JS/PHP Image Upload feature malfunctioning

Despite trying various methods and researching extensively on StkOvfl and W3 Specifications, I am still unable to solve this issue. The problem lies with a form input I have: <input type="file" multiple accept="image/*" id="item-image-upload" > In ...

Focus on a specific data set within a JSON file when working with Backbone.js

Hello! I am new to learning Backbone.js and would love some suggestions from the experts out there. Here is a snippet of my code: app.Collections.UserCollection = Backbone.Collection.extend({ model: app.Models.IdModel, url: "/test/test_data.json" ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...

Difficulty maintaining root properties in AngularJS custom directive

I recently created a custom sidebar directive, and although it is loading correctly in the designated area, I am encountering issues with the dropdown functionality of certain tags. The desired behavior is for these tags to display their inner elements whe ...

How can you categorize a multi-layered array based on a specific key?

I am currently facing an issue with a multi-dimensional array where I am attempting to group the elements based on their key values. Despite my efforts, I have been unsuccessful in properly grouping the array based on its key values. Here is the origin ...

My AJAX requests do not include any custom headers being sent

I'm facing an issue with making an AJAX request from my client to my NodeJS/ExpressJS backend. After firing the request, my backend successfully receives it but fails to recognize the custom headers provided. For example: $.ajax({ type: " ...