0

I have a single dimensional array with the below format,

let e = ["CGST:20", "SGST:20", "IGST:20", "CESS:20", "GSTIncentive:20", "GSTPCT:20"].map(i=>i.trim());

And want to match the specific string in the array, say for example, match the part of the string "IGST" in the "IGST:20".

I have tried in the below way, but it always matching the first key in the array,

if(/^IGST:/.test(e)){
  console.log("matched")
} else {
  console.log("Not matched")
}
vishnu
  • 4,377
  • 15
  • 52
  • 89
  • 1
    *"but it always matching the first key in the array"* No, it's always matching the array's contents after they've been converted to a string. – T.J. Crowder Oct 27 '20 at 12:08
  • @T.J.Crowder - can you please suggest better approach to solve this? – vishnu Oct 27 '20 at 12:11
  • Does this answer your question? [In javascript, how do you search an array for a substring match](https://stackoverflow.com/questions/4556099/in-javascript-how-do-you-search-an-array-for-a-substring-match) – Heretic Monkey Oct 27 '20 at 12:19

1 Answers1

1

If your goal is to find out if that regular expression matches any entry in the array, you can use the some function for that:

if (e.some(entry => /^IGST:/.test(entry)) {
    console.log("matched")
} else {
    console.log("Not matched")
}

If you want to find the matching entry, use find instead. If you want its index, use findIndex.

Details on MDN.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875