I have a list of array. I want to get the items that start with "tar" and number followed by it
var array = ["dataseqno", "yrsno", "tar01", "tar02", "tar03", "tar04", "tar05", "tar06", "tar07", "tar08", "tar09", "tar10", "tar11", "tar12", "status"]
I will do the loop to this array and check using regex. This is the regex I have tried. But I couldnot solve number followed by 'tar'.
.match(/^tar+\[0-9]/)
Use filter() on the array, and change your regex to ^tar[0-9]+ like so:
var array = ["dataseqno", "yrsno", "tar01", "tar02", "tar03", "tar04", "tar05", "tar06", "tar07", "tar08", "tar09", "tar10", "tar11", "tar12", "status"];
var match = array.filter(str => str.match(/^tar[0-9]+/));
console.log(match);
This checks if the element starts with tar at the start of the string, then contains any digits afterwards.
Breakdown of the regex, character by character:
^
Match the start of the string
tar
Match the string tar
[0-9]
Match any characters in the character set 0-9 (will match 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+
Match one or more of the previous selector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With