|
Techniques for text String ManagementWhen you load a text string into a Variable, the Variable automatically gains certain Methods which you can use to make changes to the text. These are called string Methods.
A good example of this is the charAt() Method, which tells you what letter (or "character") is at a given position in the text string. The term "position" refers to its numerical position in the sequence of text, and as usual, you start counting with 0. That means the first letter in a text string is at position 0. Here's how you use the charAt() Method:
To try this Function yourself, click this button: As with all of the text string Methods discussed in this section, the charAt() Method takes an argument and returns a value. In this case, the argument is a number position and the returned value is the character in the text string that is at that position.
The indexOf() Method works like the charAt() Method in reverse. It takes a small text string as an argument and returns a number indicating the position of the small text string within a bigger text string. If the small text string is not present in the bigger text string, the indexOf() Function returns the number -1.
Try it yourself yourself, click this button:
With the substring() Method, you can select and extract chunks of text based on their numerical positions within larger text strings.
Try it yourself, click this button:
Suppose you want pull some information off of a form on a Web page. In this case it's a phone number and people often put their area code in with their phone number, even though there is a separate entry on the form for that. Here's a Function that will separate the area code from the phone number. (Note that we are detecting the area code by searching for the "(" character. This may add some confusion when you look at this since we use a lot of parentheses in the Function already.):
In order to keep this example simple, it doesn't perform multiple tests. For instance, this script could also have detected area codes written in the following formats: 123-456-7890, or 123.456.7890, by using other combinations of string Methods. |