When DOM ready, I would like to check if an element on the page contains one of three strings. Currently, I am doing it like this, but this is not working as expected because indexOf is usually used in combination with arrays:
jQuery('li.woocommerce-order-overview__payment-method.method')[0].innerHTML.indexOf('iDEAL' || 'Sofortbanking' || 'Bancontact / MisterCash') > 1
How can I rewrite this in the most effective way to check if the element contains one of the three strings?
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`
Here's my try on it.
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 } }
Or, if you want to use a RegEx, which is not necessarily better:
var html; html = $("li.woocommerce-order-overview__payment-method.method").html(); if (html.match(/(?:iDEAL|Sofortbanking|Bancontact.*MisterCash)/)) { // it contains one of those strings }
If you want to get the Stein which is present, Use match
function.
If you just want to check whether it is there or not, then use the test
in JavaScript
/(iDEAL|Sofortbanking|Bancontact|MisterCash){1,}/.test(
jQuery('li.woocommerce-order-overview__payment-method.method')[0].innerHTML);
The regular expression
/(iDEAL|Sofortbanking|Bancontact|MisterCash){1,}/
Will match 1 or more occurances of that words
You can use an array of needles, and then Array.some
to check if the element contains any of them
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 ) );
The || (Or operator) does not work that way, I would suggest using the || outside of indexOf() Like so
indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1
indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1
Have a Look at a similar answer here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.