我無法讓 IndexOf 在 GAS 中正確匹配
我在這里測驗了我的正則運算式:https : //regex101.com/r/0cK6xQ/1
只要字串中有空格, indexOf() 就不會匹配。我什至嘗試將正則運算式設定為let contactRegExp = /(contact 1 Type)/i ; ,這應該是樣本陣列中第二個元素的直接匹配,它會爆炸。
function setContactTypes(){
//Find all contact Type columns
let contactRegExp = /(contact [\d]* Type)/i ;
var headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type'];
var hitArray = [];
var i = -1;
while ((i = headerIndexList.indexOf(contactRegExp,(i 1))) != -1){
hitArray.push(i);
}
}
hitArray 應該回傳 [1,3]
我認為它與陣列與字串有關,但我一生都無法弄清楚。
uj5u.com熱心網友回復:
不幸的是,Array.prototype.indexOf()不能使用正則運算式。那么在你的情況下,為了實作你的目標,下面修改的腳本怎么樣?
修改后的腳本:
function setContactTypes(){
let contactRegExp = /(contact [\d]* Type)/i ;
var headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type'];
var hitArray = headerIndexList.reduce((ar, e, i) => {
if (contactRegExp.test(e)) ar.push(i);
return ar;
}, []);
console.log(hitArray) // When your "headerIndexList" is used, [1, 3] is returned.
}
測驗:
顯示代碼片段
let contactRegExp = /(contact [\d]* Type)/i ;
var headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type'];
var hitArray = headerIndexList.reduce((ar, e, i) => {
if (contactRegExp.test(e)) ar.push(i);
return ar;
}, []);
console.log(hitArray)
參考:
- Array.prototype.indexOf()
- 測驗()
- 降低()
添加:
例如,以下腳本對您的情況有用嗎?
let contactRegExp = /(contact [\d]* Type)/i;
var headerIndexList = ['dummy1', 'contact 1 Type', 'dummy2', 'contact 2 Type'];
var hitArray = [];
for (var i = 0; i < headerIndexList.length; i ) {
if (contactRegExp.test(headerIndexList[i])) {
hitArray.push(i);
}
}
console.log(hitArray)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332755.html
標籤:谷歌应用程序脚本
上一篇:專案不能被添加到一個陣列中
