Reputation: 124
"if" gives me more answers.. How to get only first? Thanks people. http://jsfiddle.net/TsxBy/
var content = "var=xyz-id=2,var=abc-id=1,var=bcd-id=7,var=abc-id=1,var=hij-id=4,var=xyz-id=2";
content = content.split(',');
for (i = 0; i < content.length; i++) {
var temp = content[i].match(/\d/);
if (temp == '1') {
alert('match 1'); // how to response only first "matched"?
}
if (temp == '2') {
alert('match 2'); // same here
}
}
Upvotes: 0
Views: 124
Reputation: 2311
I think I understand your issue a bit. Please check this fiddle update if it's what you need.
var content = "var=xyz-id=2,var=abc-id=1,var=bcd-id=7,var=abc-id=1,var=hij-id=4,var=xyz-id=2";
content = content.split(',');
var ctr1 = 0, ctr2 = 0;
for (i = 0; i < content.length; i++) {
var temp = content[i].match(/\d/);
console.log(temp[0]);
if (temp[0] == '1' && ctr1 == 0) {
alert('match 1');
ctr1++;
}
if (temp[0] == '2' && ctr2 == 0) {
alert('match 2');
ctr2++;
}
}
Upvotes: 2
Reputation: 76
Your code is checking for a single integer in each element of the array, resulting in 6 iterated checks, 4 of which have a matching number to one of your if statements, which is what you get, 4 alerts.
If you want it to stop looking after it matches the first number, use a break at the end of the desired if statement.
Upvotes: 0