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")
}
3
  • 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. Commented Oct 27, 2020 at 12:08
  • @T.J.Crowder - can you please suggest better approach to solve this? Commented Oct 27, 2020 at 12:11
  • Does this answer your question? In javascript, how do you search an array for a substring match Commented Oct 27, 2020 at 12:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.