簡體   English   中英

使用 JavaScript 匹配數組中的字符串部分

[英]Match the part of a string in the array using JavaScript

我有一個具有以下格式的一維數組,

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

並想匹配數組中的特定字符串,例如匹配“IGST:20”中字符串“IGST”的部分。

我試過下面的方法,但它總是匹配數組中的第一個鍵,

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

如果您的目標是找出該正則表達式是否與數組中的任何條目匹配,您可以為此使用some function:

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

如果要查找匹配的條目,請改用find 如果你想要它的索引,請使用findIndex

MDN 上的詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM