Utilizing regular expressions

Regular expressions are created to compare a string to a type of pattern. These patterns could be uppercase letters only, letters only, or numbers to name some examples. The variety of selectors available are numerous leading to the creation of custom patterns for any string comparison.

In this instance, my use of regular expressions is to create an input validator. This pattern incoporated the use of not, !, lowercase and uppercase letters, [a-zA-z], and spaces, [A-z\s]. Three special characters are used as quantifiers with ^ at the beginning to allow for any letter at the start of the pattern, a * at the end to check for zero or more spaces, and a $ afterwards to allow extra spaces to be allowed. These characters are enclosed between two / to have them recognized as a pattern. At the end is the action to perform which is i, a case insensitive comparison followed by “test” to determine if there is a match. All together the line reads:

!/^[a-zA-z][A-z\x]*$/i.test(parameter)

What this line will do is perform a check of the parameter that has been passed and determine if there are only case insensitive letters and spaces in the parameter. In the case I used it, the search bar is where the input validator’s actions were to take place and the requirement was to have users input a city and state. An error would appear if a number was placed anywhere in the search bar and the user would be asked to retry their search.

In future projects where comparing strings to a pattern become relevant, I will turn to using regular expressions if possible. Another function I used to create a pattern that checks for upper and lowercase letters was to create an empty array, and two variables i and j. The variable i contained A.charCodeAt(0) and j contained Z.charCodeAt(0) which gives their respective integer positions in the UTF-16 code index. The for loop was then created to compare i ≤= j and push each character between the variables onto the empty array. When finished, the alphabet would be placed into the array for use elsewhere. this same function would need to be run again for lowercase letters. This worked for what I needed however felt lengthy and convoluted when compared to using a pattern [a-zA-z] to achieve the same end.