SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jun 2005
    Location
    Kennett Square, PA USA
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Array.prototype.find won't work

    I am trying to use Array.prototype.find to search for a substring in an array. I want to search through the array as the user enters values into a form field.

    The prototype.find function works when I test it like this where I am searching for all entries that begin with "A":
    var test = theArray.find(/^A/);
    alert("test" + test); // this correctly displays the array indexes of found elements

    The problem is when I attempt to pass the parameter to a function, as follows:
    Here's the form element:
    <input name="businessType" id="businessType" type="text" size="20" value="" onkeyup="checkForMatch(this.value);">

    Here's the checkForMatch function:
    function checkForMatch(theString){
    var searchString = "/^" + string + "/i";

    var result = theCats.find(searchString);
    alert("searchString:" + searchString+ "\nresult:" + result + " \npassed value is: " + theString );

    }

    And here the prototype.find :
    Array.prototype.find = function(searchStr) {
    var returnArray = false;
    for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
    if (searchStr.test(this[i])) {
    if (!returnArray) { returnArray = [] }
    returnArray.push(i);
    }
    } else {
    if (this[i]===searchStr) {
    if (!returnArray) { returnArray = [] }
    returnArray.push(i);
    }
    }
    }
    return returnArray;
    }

    prototype.find always returns false, unless I pass the parameters in test mode as described earlier.

    I appreciate any advice you might have.

    - Jack

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are not making a regular expression, but simply passing a string that starts with a slash and ends with 'i'.

    Use the RegExp constructor:
    function checkForMatch(string){
    var searchString =RegExp( "^" + string ,'i');


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
  •