简体   繁体   中英

How to find part of a string in array jQuery

I've been trying to find a portion of a string in a couple of Array of strings without success:

I have array1 ['BA11', 'BA14', 'BA15']

and array2 ['GL156', 'GL24', 'GL31']

I wanted that it would return true when I searched for just part of the string "BA11AB", "BA15HB" or "GL156DC".

Here is the code I've been using but without success:

if($.inArray(userinput, array1) !== -1) 
        {
            alert("Found in Array1!");
        }

if($.inArray(userinput, array2) !== -1) 
        {
            alert("Found! in Array2");
        }

Thanks Nuno

var found = false;
$.each(array, function(i, val) {
    if (val.indexOf(string) >= 0) {
        found = true;
        return false;
    }
});

Seeing that OP changed his original question: http://jsfiddle.net/c4qPX/2/ is a solution for both of them (there's no really difference for the algorithm if we're searching through the array of searched keys or searched values) - the point is what to compare.

var array1 = ['BA11', 'BA14', 'BA15'];
var array2 = ['GL156', 'GL24', 'GL31'];
var search = 'GL156DC';

$.each([array1, array2], function(index, value){
    $.each(value, function(key, cell){
        if (search.indexOf(cell) !== -1)
            console.log('found in array '+index, cell);
    });
});

You can create a simple function and add it to the Array prototype (so that it can be called on any array) which searches through the array looking for sub-string matches:

JSFIDDLE

Array.prototype.containsSubString = function( text ){
    for ( var i = 0; i < this.length; ++i )
    {
        if ( this[i].toString().indexOf( text ) != -1 )
            return i;
    }
    return -1;
}

Then just use it on your arrays:

var array1 = ['12345', '78273', '34784'],
    array2 = ['JJJJJ', 'ABCDEF', 'FFDDFF'];

if( array1.containsSubString( 234 ) !== -1) 
{
    alert("Found in Array1!");
}

if( array2.containsSubString( 'DD' ) !== -1) 
{
    alert("Found! in Array2");
}

Edit

If you want to find whether an array has an element which is a sub-string of another string then:

JSFIDDLE

Array.prototype.hasSubStringOf = function( text ){
    for ( var i = 0; i < this.length; ++i )
    {
        if ( text.toString().indexOf( this[i].toString() ) != -1 )
            return i;
    }
    return -1;
}

var array3 = [ 'AB11' ];

if( array3.hasSubStringOf( 'AB11HA' ) !== -1) 
{
    alert("Array3 contains substring");
}

Edit 2

Just combine both the previous functions:

JSFIDDLE

Array.prototype.containsSubStringOrHasSubstringOf = function( text ){
    for ( var i = 0; i < this.length; ++i )
    {
        if (    this[i].toString().indexOf( text.toString() ) != -1
             || text.toString().indexOf( this[i].toString() ) != -1 )
            return i;
    }
    return -1;
}

var testArrays = [
        ['BA11ABC', 'BAGL156DC14', 'BA15HC'],
        ['GL156DC', 'GL166DC', 'GL31BA11AB'],
        ['BA11', 'BA14', 'BA15'],
        ['GL156', 'GL24', 'GL31']
    ],
    testValues   = [ "BA11AB", "BA15HB", "GL156DC" ],
    results = [ 'Results:' ];

var test = function( str, arr ){
    var i = arr.containsSubStringOrHasSubstringOf( str );
    if ( i !== -1 )
        results.push( JSON.stringify( arr ) + ' matches ' + str + ' on ' + arr[i] );
    else
        results.push( JSON.stringify( arr ) + ' does not match ' + str );
};

for ( var i = 0; i < testArrays.length; ++i )
    for ( var j = 0; j < testValues.length; ++j )
        test( testValues[j], testArrays[i] );

alert( results.join('\n') );

try something like this

 return array1.toString().indexOf(userinput)!=-1;

if problem with comma than

 return array1.join('|').indexOf(userinput)!=-1;

use space if any problem arrive

return array1.join(' ').indexOf(userinput)!=-1;

I'm not sure if you are familiar with underscore js , but you could use something like this:

var array = ['JJJJJ', 'ABCDEF', 'FFDDFF'];
var search = "JJJ";
var found = _.some(array, function(value) {
    return value.indexOf(search)!=-1;
});

alert(found);

see fiddle .

seen the answers of the others and I really like the toString() answers: array.toString().indexOf(search)!=-1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM