0

Javascript string search string in array not working here is my code

Mycode

var array = ["foo","fool","cool","god",'searchstring'];
 var src_keyword="";
 $("#search_str").click(function(){
   src_keyword=$("#str_search").val();
  find(array,src_keyword)
 });

 function find(arr,src_keyword1) {
 var result = [];
 alert(src_keyword1);
//src_keyword1="oo";
for (var i in arr) {
    var search = new RegExp(src_keyword1, "gi");
    if (arr[i].match(search)) {
        alert(arr[i])
        result.push(arr[i]);

    }
 }

return result;
}

Html

 <input type="text" id="str_search" value=" "/>
 <input type="button" id="search_str" value="search" />

thanks in advance

Edited by sri.: spelling

3
Contributors
5
Replies
25
Views
4 Years
Discussion Span
Last Post by paulkd
0

I think you left out the display result bit....

$(document).ready(function(){

    var array = ["foo","fool","cool","god",'searchstring'];
    var src_keyword="";
    $("#search_str").click(function(){
        src_keyword=$("#str_search").val();
       result =  find(array,src_keyword);
       console.log(result);
    });
});

function find(arr,src_keyword1) {
    var result = [];
//    alert(src_keyword1);
    //src_keyword1="oo";
    for (var i in arr) {
        var search = new RegExp(src_keyword1, "gi");
        if (arr[i].match(search)) {
            result.push(arr[i]);
        }
    }
    return result;
}
0

see my post

 if (arr[i].match(search)) {
 alert(arr[i]);
 result.push(arr[i]);
 }
1
if (arr[i] == search) {
 alert(arr[i]);
 result.push(arr[i]);
 }

try it like this

0

sri,

As far as I could tell your original code worked, you just didnt output the result. I outputted the result to console on my line 8.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.