Please help - split string into array and do a RegExp search in the array

Discussion in 'JavaScript' started by spaceman12, Mar 16, 2011.

  1. #1
    I have been trying to sort this out by myself but it seems like I just can't figure to work it out correctly.

    Suppose, I have a string like this-
    
     var string="Where are you and Iam so sorry I cannot sleep I cannot dream tonight";
    
    Code (markup):
    Here, lets assume that the string that I want to search for it is Where
    
    var search= new RegExp["^Where$"];
    
    Code (markup):
    I'm sure the object split() has got to do something with string and then do a testing.

    Like this
    
    var array=new array();
    array=string.split(" ");
    
    if(search.test(array))
    {
    document.write('true');
    }
    
    Code (markup):
    Despite all my efforts to make it work, I just can't.

    In php, we could have easily split the string into arrays using explode and call the function
    
    if(in_array($search,$array))
    {
    echo "true";
    }
    
    Code (markup):
    Please help(I'm just not very familiar with javascript) .Thanks :)
     
    spaceman12, Mar 16, 2011 IP
  2. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #2
    How about this?
    
    var string="Where are you and Iam so sorry I cannot sleep I cannot dream tonight";
    if (string.indexOf("Where") != -1) document.write("true");
    
    Code (markup):
     
    Cash Nebula, Mar 16, 2011 IP