0

I am trying to find some words in some array and I did something like this:

    $("#get").click(function(){
    $(".name").each(function(){
        var fisier = $(this).text();
        alert($.inArray("migr", fisier));
    });
});

I have "migr" in almost every fisier var but I get only -1. What am I doing wrong ?

Thanks!

5
  • It will match the exact word only.. Commented Feb 27, 2014 at 8:37
  • 3
    fisier is just a string not an array. Commented Feb 27, 2014 at 8:38
  • can you provide the html and the data in that Commented Feb 27, 2014 at 8:41
  • fisier variable is string not array & you try to redeclare it again and again Commented Feb 27, 2014 at 8:42
  • try splitting the string fisier like fisier.split(/\b/) Commented Feb 27, 2014 at 8:44

4 Answers 4

1

You could check for the keyword with JavaScript indexOf method. This is check for each element of the array:

$("#get").click(function(){
    $(".name").each(function(){
        var fisier = $(this).text();       
        if(fisier.indexOf("migr") !=-1){
           alert('Keyword found');
        }else{
           alert('Keyword not found');
        } 
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

With the help of inArray function you can check value exists in array or not. $.inArray function return the index of element. If element not exist in array it will return -1. So, we can check it very simply weather a value exist in array or not.

Comments

1

inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array.

So, to check if an item is in the array, use:

if(jQuery.inArray("test", myarray)!==-1) 

or

if($.inArray("test", myarray)!==-1) 

as inArray will return -1, if the element was not found.

1 Comment

If you want to return a boolean, use a tilde (~). if (!~$.inArray(0, [1, 2, 3, 4, 5])) { // returns false, not -1 }.
0

fisier is just a string not an array.

I guess this is what you want:

$("#get").click(function(){
    var names = $('.name').map(function() {
        return $(this).text();
    });
    alert($.inArray("migr", names));
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.