SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member stix_fs's Avatar
    Join Date
    Nov 2010
    Location
    United Kingdom
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Searching for multiple words within a string or Array


    How would one search for more than one one simultaneously?

    I have this function:

    =========================================================

    var flix = ["Any items left unattended on this table" , "Hello, World"];

    function Multiwords(s){


    var a = flix[0].toLowerCase();

    var b = s.toLowerCase();

    var result = a.indexOf(b)

    if (result >= 0)

    alert ('Found');
    else
    alert('Not Found');
    }

    Multiwords("ANY")


    =========================================================

    It's pretty basic, it just searches through the first index of var flix and tells me if the parameter (s) is 'found' or 'not found'. I made it not to be case sensitive.

    However, how would I search for multiple words for example:

    Multiwords("ANY items This")


    and if any combination of 'ANY' or 'items' or 'This' is found, i still get my alert message of 'Found'?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    This works for me

    Code JavaScript:
    function Multiwords(s){
        var a = flix[0].toLowerCase();
     
        for(var i=0; i<s.length; i++){
            if (a.indexOf(s[i].toLowerCase()) != -1){
                alert('Found');
            } else {
                alert('Not Found');
            }
        }
    }
     
    Multiwords(["ANY","UNATTENDED","HELLO"]);

  3. #3
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I presume you want to search an array of strings for any occurrence of the words in a specified string.

    Code:
    <script type="text/javascript">
    
    function wordsInStringArray( arr, str ) /* search array of strings 'arr' for any word in string 'str' */
    {
     var wordGroup  = str.replace( /^\s+|\s+$/g, "" ).split( /\W+/ ), found = null, re;
       
     for( var i = 0; i < arr.length && !found;  i++ )   
      for( var j = 0, wLen = wordGroup.length; j < wLen && !found; j++ )   
       if( ( re = new RegExp( "\\b" + wordGroup[ j ] + "\\b", "i" ) ).test( arr[ i ] )  )
        found = { word : arr[ i ].match( re ), elem : arr[ i ] };
          
     return found;   
    }
    
    
    var stringArray = [ "jumped over", "the lazy dog", "the swift cat" ],
        wordString = " a cat, a dog, a rabbit and a hamster",
        result;
    
    if( ( result = wordsInStringArray( stringArray, wordString ) ) )
     alert( '"' + result.word + '"' + '\n\nfound in\n\n"' + result.elem + '"');
    
    </script>
    Tab-indentation is a crime against humanity.

  4. #4
    SitePoint Member stix_fs's Avatar
    Join Date
    Nov 2010
    Location
    United Kingdom
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But what if I wanted to return only one alert box of found and not found?

    For example if I call this function:

    Multiwords(["ANY","UNATTENDED","HELLO"]);

    I wanted the alert of to say 'Not Found' - (because 'Hello' is not present in filx[0]). I wouldn't want to have three alert boxes of ''found, found, and 'not found'.

    So if a combination of 3 words includes a word that is not in flix[0], the result would be 'Not Found', even though 2 of the words may appear in flix[0].


    I don't know if that makes sense?

  5. #5
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I misunderstood at first so have ended up coming up with two options. One that searches with OR i.e. if any of the words match then found.

    And one that matches with for AND, which is what I think you want. (unfortunately there isn't an && in javascript regular expressions)

    Search to see if any of the words come up.
    Code JavaScript:
    function multiSearchOr(text, searchWords){
      // create a regular expression from searchwords using join and |. Add "gi".
      // Example: ["ANY", "UNATTENDED","HELLO"] becomes
      // "ANY|UNATTENDED|HELLO","gi"
      // | means OR. gi means GLOBALLY and CASEINSENSITIVE
      var searchExp = new RegExp(searchWords.join("|"),"gi");
      // regularExpression.test(string) returns true or false
      return (searchExp.test(text))?"Found!":"Not found!";
    }

    Code JavaScript:
    console.log(multiSearchOr("Any items left unattended on this table", ["ANY","UNATTENDED","HELLO"])); // Found!!
    console.log(multiSearchOr("Any items left unattended on this table", ["apple","orange","strawberry"])); // Not Found!!

    Search to see if all the words come up.
    Code JavaScript:
    function multiSearchAnd(text, searchWords){
      // create a regular expression from searchwords using join and |. Add "gi".
      // this time put our search words inside back reference catching brackets
      // Example: ["ANY", "UNATTENDED","HELLO"] becomes
      // "(ANY)|(UNATTENDED)|(HELLO)","gi"
      // (..) are backreferences. | means OR. gi means GLOBALLY and CASEINSENSITIVE
      var searchExp = new RegExp("("+searchWords.join(")|(")+")","gi");
      // use match to return an array of backreference matches. If the array length doesn't match searchWords then Not found!!
      return (text.match(searchExp).length == searchWords.length)?"Found!":"Not found!";
    }

    Code JavaScript:
    console.log(multiSearchAnd("Any items left unattended on this table", ["ANY","UNATTENDED","hello"])); // Not Found!!
    console.log(multiSearchAnd("Any items left unattended on this table", ["Any","UNattended","taBle"])); // Found!!

    The 2 functions uncommented

    Code JavaScript:
    function multiSearchOr(text, searchWords){
      var searchExp = new RegExp(searchWords.join("|"),"gi");
      return (searchExp.test(text))?"Found!":"Not found!";
    }
     
    function multiSearchAnd(text, searchWords){
      var searchExp = new RegExp("("+searchWords.join(")|(")+")","gi");
      return (text.match(searchExp).length == searchWords.length)?"Found!":"Not found!";
    }

    edit: The multiSearchAnd is flawed. If you have multiple matches like

    multiSearchAnd("Any items left unattended on any table", ["ANY","UNATTENDED","hello"])

    it will return found!!

    will work on a solution

    RLM

  6. #6
    SitePoint Addict
    Join Date
    Nov 2008
    Location
    Thailand
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Regular expressions getting the better of me today. Still looking into a reg expression to do the job.

    Code JavaScript:
    function multiSearchAnd(text, searchWords){
      var currTest;
      while (currTest = searchWords.pop()){
        if (!text.match(new RegExp(currTest,"i"))) return "Not Found!";
      }
      return "Found!";
    }


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •