2

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?

2
  • Check this out: jsfiddle.net/hrBTX Commented Aug 3, 2012 at 17:43
  • This was also very helpful thank you canon Commented Aug 3, 2012 at 18:31

3 Answers 3

1

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);​

Here is a fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

conversion to a number will drop insignificant digits (e.g. '0010' will become 10)
@jbabey -- true, your comment helped me simply this, thanx
This was perfect, I reconfigured to fit my logic and it works fine, thanks very much to everyone
@deckard If this answer helped you, please consider upvoting and or accepting it. Its how SO works
0

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();
}

Comments

0

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 {
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.