How to use IndexOf in JQuery How to use IndexOf in JQuery javascript javascript

How to use IndexOf in JQuery


That's because it would be looking for the string '4289||78843', which doesn't exist in the target I'm assuming. Logical operators can't just be tossed in anywhere, only where there are actual values to logically operate on. Something like this:

if(($('#this').val().indexOf('4289') > -1) ||   ($('#this').val().indexOf('78843') > -1))

The return value of the indexOf() function is the numeric index of that value in the target value, or -1 if it's not found. So for each value that you're looking for, you'd want to check if it's index is > -1 (which means it's found in the string). Take that whole condition and || it with another condition, and that's a logical operation.

Edit: Regarding your comment, if you want to abstract this into something a little cleaner and more generic you might extract it into its own function which iterates over a collection of strings and returns true if any of them are in the target string. Maybe something like this:

function isAnyValueIn(target, values) {    for (var i = 0; i < values.length; i++) {        if (target.indexOf(values[i]) > -1) {            return true;        }    }    return false;}

There may even be a more elegant way to do that with .forEach() on the array, but this at least demonstrates the idea. Then elsewhere in the code you'd build the array of values and call the function:

var values = ['4289', '78843'];var target = $('#this').val();if (isAnyValueIn(target, values)) {    // At least one value is in the target string}