Pergunta

I apologize if this is a duplicate question. It's such a use-case question that it seems everyone has their own version.

I'm wondering if this can be simplified:

if ($('.taxclass').text().indexOf(tax1)>-1 || $('.taxclass').text().indexOf(tax2)>-1) {}
Foi útil?

Solução

It's pretty simple as it stands, but you could make it a bit less redundant mainly by getting the elements text only once and reusing the variable:

var text = $('.taxclass').text();
if (text.indexOf(tax1)>-1 || text.indexOf(tax2)>-1) {

}

A further note could be to reduce the traversal of the DOM by using an identifier and looking only for a distinct element (if that suits your needs) instead of every possible thing that has the class taxclass.

Outras dicas

var txt = $('.taxclass').text();
if (txt.indexOf(tax1)>-1 || txt.indexOf(tax2)>-1) {}

One super quick way would be not to duplicate $('.taxclass').text()

Try something like

var tax = $('.taxclass').text();
if (tax.indexOf(tax1)>-1 || tax.indexOf(tax2)>-1) {}

You can store $('.taxclass').text() in a variable, or use regex.

var str = $('.taxclass').text();

if (str.indexOf(tax1) > -1 || str.indexOf(tax2) > -1)

// Or with regex
if(/(text1)|(text2)/.test($('.taxclass').text())
{}

Quick and dirty:

text.indexOf(tax1+"~"+tax2)>-1

Functional, works on n strings, but verbose:

[tax1, tax2].some(function(s) { return s.indexOf(text)>-1 })

As a prototype:

String.prototype.foundIn = function() {
    var s=this; return Array.prototype.slice.call(arguments).some(function(m)
       {return m.indexOf(s)>-1});
};

Usage:

$('.taxclass').text().foundIn(tax1, tax2)

What about:

f = function (x) { return $('.taxclass').text().indexOf(x) > -1; }
if (f(tax1) || f(tax2)) {}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top