Chalupa
Chalupa

Reputation: 367

skipping spaces with javascript

here i have a javascript/html code. My code is supposed to read a string of one or more zipcodes from the user and return the first non-valid zipcode. It should ignore spaces. the user can only use the zipcodes 48103, 48104, 48105, 48106, 48197, 48198. anything else should be invalid. My code mostly works except when the user puts in more than one space to separate the zipcodes. so for example if the user enters "48103, space , space, space, 98324" my program should return 98324 but it just returns the space. Can anyone help? Thank you

<html>
    <head>
        <title>Due 03/30</title>

        <script>

            function test()
            {   

                var usr = prompt("Enter a string of zip codes separated by spaces: ");
                var array = [];
                array = usr.split(" ");
                //alert (array);
                var pattern = /(4810[3-6])|(4819[7-8])/;
                var str;
                var isBad = false;

                var i;
                for (i =0; i < array.length; i++)
                {    
                    str = array[i];
                    if (!str.match(pattern) && str != " ")
                       {  
                          alert ("The zipcode " + str + " is not a valid zipcode!");
                          isBad = true;
                          break;
                       }
                }

                if (isBad === false)
                  alert("All zipcodes are valid");

               }
        </script>
    </head>

    <body>

        <button onClick="test();">Test String</button>

    </body>
</html>

Upvotes: 0

Views: 388

Answers (2)

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

Replace multiple spaces with single spaces within the split, using a regular expression:

array = usr.split(/ +/g);

(Thanks to @HBP for the edit.)

You can then replace this code:

if (!str.match(pattern) && str != " ")

… with:

if (!str.match(pattern))

Upvotes: 2

jkd
jkd

Reputation: 1045

Your loop:

for (i =0; i < array.length; i++)
{    
    str = array[i];
    if (!str.match(pattern) && str != " ")
       {  
          alert ("The zipcode " + str + " is not a valid zipcode!");
          isBad = true;
          break;
       }
}

Should be:(str != "" not str != " ")

for (i =0; i < array.length; i++)
{    
    str = array[i];
    if (!str.match(pattern) && str != "") // No space
       {  
          alert ("The zipcode " + str + " is not a valid zipcode!");
          isBad = true;
          break;
       }
}

This is because when you split the string: "JavaScript is Awesome!" into spaces, then the javascript sees it as "JavaScript"+Space+"is"+Space+""+Space+"Awesome!".

Upvotes: 1

Related Questions