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)
);