Many string searches are simple. A user looks for a particular word or other data in a string, and your application finds it. The following example shows one technique for performing a simple search.
In this example, the code begins by creating a global variable that contains a search string the user can interact with. You could change this string to anything you want for experimentation purposes.
The FindString() function is connected to the Find It button. The first task is to obtain the value that the user wants to find and place it in FindValue. The example then uses the indexOf() function on SearchString to locate FindValue and place the position in Result.
The second task is to interpret the results. The example looks for one of three values in Result. When Result is 0, the user hasn’t provided any input, and the example asks the user to provide some. When Result is –1, the user has supplied a search string that doesn’t appear in the original string, and the example lets the user know that the search string wasn’t found.
When Result is a positive value, the application displays the position of the search string in the original string onscreen.
Not all searches are simple. Sometimes a user needs to perform a complex search based in a regular expression — one in which there are wildcard search terms. The following example shows a simple way to implement such a search.
The example begins by defining a global search string. It then defines the FindString() function that’s used to perform the actual search. Compare this version of FindString() with the FindString() function you see they have some similarities, but that this version’s much shorter (even though it’s far more flexible).
The FindString() function obtains the search string and places it in FindValue. It then obtains any search modifiers and places them in Modifiers. The example creates a new RegExp object, Pattern, that’s a combination of the search string and search modifiers.
At this point, the code uses the match() function on SearchString to produce a result. The output is actually an array of values that you could use to locate each incidence of the search term in the search string. The array elements appear onscreen separated by commas.
Notice that this search uses a bracketed regular expression for input. In addition, the search modifiers appear in the second field after the search expression. This example is fully capable of using any combination of regular expression elements, so try various combinations to see how they work for you.