2 回答

TA貢獻1860條經驗 獲得超9個贊
您可以使用正則表達式來檢查與要求匹配的給定字符串。喜歡這個
var regEx = /(^FOR)|(.*EMPEROR.*)/i;
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!" ]
array.filter(function(str) { return regEx.test(str) }) // ["FOR THE EMPEROR!!"]
對于區分大小寫的,在正則表達式中刪除 i,例如:/(^FOR)|(.*EMPEROR.*)/
var regEx = /(^FOR)|(.*EMPEROR.*)/i;
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!", "For the champion", "And the EMPEROR" ]
const result = array.filter(function(str) { return regEx.test(str) })
console.log({result})

TA貢獻1880條經驗 獲得超4個贊
如果需要支持較低版本的 IE,請使用 代替 。indexOfincludes
let array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!"];
console.log(array.filter( function(el) {
return el.indexOf("EMPEROR") > -1 && el.split(" ")[0] == "FOR"
}))
添加回答
舉報