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?
Search for a number in a string or in an array
Collapse
X
-
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 -
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');Thank you for your help!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; } }Comment
-
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 regardsComment
Comment