Reputation: 35
I have a string of data which will often read like this: "0010, 0010, 0030". I need to validate that string to the user by setting up an alert if all of the numbers do not match. So if the string looks like this "0010, 0010, 0010" then there is no issue and my logic proceeds as planned. But if it looks like this: "0010, 0010, 0030", then I need to alert the user that they chose an incorrect operation (where 0010, and 0030 are operations in the logic), and they must reselect. Any ideas?
Upvotes: 2
Views: 168
Reputation: 120278
Just split the string on ,
and then compare the entries.
Something like the following (I haven't tested this, but its an outline)
var input = "0010, 0010, 0010",
tokens = input.split(','),
result = true;
for (var i = 0; i <= tokens.length - 1; i++) {
if (i <= tokens.length - 2) {
// get rid of whitespace
if (tokens[i].replace(/\s/g, '') !== tokens[i+1].replace(/\s/g, '')) result = false;
}
}
alert(result);
Upvotes: 1
Reputation: 46657
i would recommend a regular expression:
// gives you an array with values "0010", "0010", and "0030"
var matches = '0010, 0010, 0030'.match(/(\d+)/);
Then just loop over the matches and compare them their neighbor. If any are not common, you have your answer so break out of the loop.
var allMatch = true;
for (var i = 1; i < matches.length; i++) {
if (matches[i-1] !== matches[i]) {
allMatch = false;
break;
}
}
if (allMatch) {
...
} else {
...
}
Upvotes: 0
Reputation: 840
Try this:
var split="0010, 0010, 0030".split(", ");
var ok = true;
for (i = 0; i < split.length - 1; i++)
{
if (split[i] != split[i + 1])
{
//reset_logic();
ok = false;
break;
}
}
if (ok)
{
//all_good();
}
Upvotes: 0