![](/img/trans.png)
[英]JavaScript/jQuery - Check if string contains one of the keywords
[英]Check if element contains one of three string in JavaScript or jQuery
當DOM准備就緒時,我想檢查頁面上的元素是否包含三個字符串之一。 目前,我正在這樣做,但是由於indexOf通常與數組結合使用,因此無法正常工作:
jQuery('li.woocommerce-order-overview__payment-method.method')[0].innerHTML.indexOf('iDEAL' || 'Sofortbanking' || 'Bancontact / MisterCash') > 1
如何以最有效的方式重寫此代碼,以檢查元素是否包含三個字符串之一?
var html = ...
var match = new Array('iDEAL' , 'Sofortbanking' , 'Bancontact / MisterCash');
var found = false;
for(var i=0;i<3;++i){
if(html.indexOf(match[i])!=-1){
found = true;
}
}
//use `found`
這是我的嘗試。
var html, salient; html = $("li.woocommerce-order-overview__payment-method.method").html(); salient = [ "iDEAL", "Sofortbanking", "Bancontact / MisterCash" ]; for (i = 0; i < salient.length; i++) { if (html.indexOf(salient[i]) !== -1) { // it contains string i } }
或者,如果您想使用RegEx,則不一定更好:
var html; html = $("li.woocommerce-order-overview__payment-method.method").html(); if (html.match(/(?:iDEAL|Sofortbanking|Bancontact.*MisterCash)/)) { // it contains one of those strings }
如果要獲取存在的Stein,請使用match
功能。
如果您只想檢查它是否存在,請在JavaScript中使用test
/(iDEAL|Sofortbanking|Bancontact|MisterCash){1,}/.test(
jQuery('li.woocommerce-order-overview__payment-method.method')[0].innerHTML);
正則表達式
/(iDEAL|Sofortbanking|Bancontact|MisterCash){1,}/
將匹配該單詞的1個或多個出現
您可以使用針陣列,然后使用Array.some
檢查元素是否包含其中的任何一個
let needles = ['iDEAL', 'Sofortbanking', 'Bancontact', 'Bancontact / MisterCash'];
let haystack = $('li.woocommerce-order-overview__payment-method.method').html();
let result = needles.some( needle => haystack.includes( needle ) );
|| (或運算符)不能那樣工作,我建議使用|| 在indexOf()之外像這樣
indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1
indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1
在這里看看類似的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.