Search for a number in a string or in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Esmeralda
    New Member
    • Feb 2008
    • 8

    Search for a number in a string or in an array

    What would be the best way to search for a number within a string or an array in javascript? I'm currently using indexof - but if I am searching for 1, would it also return true if the number ends up being 11 or 111?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    you are right ... but you may use a regEx here :

    [CODE=javascript]var s = 'adgf1';
    var t = s.match(/1{1}/g);

    alert(t.length) ;[/CODE]
    that would give you an array of all occurences of 1 in the string s ... but what do you really want to check exactly?

    kind regards

    Comment

    • Esmeralda
      New Member
      • Feb 2008
      • 8

      #3
      I hadn't thought of using regex, but that may work as a great possiblity, thanks :) .

      What I'm actually trying to do is look for a number within an array. The number is dynamically set as is the array. Indexof was working correctly, but then I realized my error.

      Here is a snippet:
      Code:
       var dispCA = new Array(<cfoutput query="getCA">#id#<cfif getCA.currentRow LT getCA.recordCount>,</cfif></cfoutput>);
      var dispSup = new Array(<cfoutput query="getSup">#id#<cfif getSup.currentRow LT getSup.recordCount>,</cfif></cfoutput>);
      var contID = document.getElementsByName('contactID');
      Code:
      for(var i=0;i<contID.length;i++)
      { 						
       if(dispCA.join().indexOf(contID[i].value)>=0)
       {
      	contID[i].checked = true;
       }
       else
       {
      	contID[i].checked = false;
       }
      }
      Thank you for your help!

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        hi ...

        since you use arrays you may find the following article useful. I wouldn't use indexOf ... just 'real'-compare the id with the array-values ... something like this:

        [CODE=javascript]var a = ['2', '1', 'a'];

        function arr_contains(ar r, val) {
        var ret = false;

        for (var i = 0, l = arr.length; i < l; i++) {
        if (arr[i] === val) {
        ret = true;
        break;
        }
        }

        return ret;
        }

        // usage
        alert(arr_conta ins(a, '1'));
        [/CODE]
        kind regards

        Comment

        • Esmeralda
          New Member
          • Feb 2008
          • 8

          #5
          Thank you again. I ended up using regEx and the search() function.
          Code:
          var contnum = new RegExp('/,?' + contID[i].value + ',?/');
          if(dispCA.join().search(contnum)>=0)
          {
          It seems to work okay...

          Comment

          Working...