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?
3 Answers
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);
4 Comments
jbabey
conversion to a number will drop insignificant digits (e.g.
'0010' will become 10)hvgotcodes
@jbabey -- true, your comment helped me simply this, thanx
Deckard
This was perfect, I reconfigured to fit my logic and it works fine, thanks very much to everyone
hvgotcodes
@deckard If this answer helped you, please consider upvoting and or accepting it. Its how SO works
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 {
...
}