In this chapter we've looked at some more advanced methods of the String object and how their use can be optimized using regular expressions.
To recap, the chapter covered the following points:
The split() method splits a single string into an array of strings. We pass a string or a regular expression to the method that determines where the split occurs.
The replace() method allows us to replace a pattern of characters with another pattern that we specify as a second parameter.
The search() method returns the character position of the first pattern matching that given as a parameter.
The match() method matches patterns, returning the text of the matches in an array.
Regular expressions allow us to define a pattern of characters that we want to match. Using this pattern, we can perform splits, searches, text replacement, and matches on strings.
In JavaScript the regular expressions are in the form of a RegExp object. A RegExp object can be created using either myRegExp = /myRegularExpression/ or myRegExp = new RegExp("myRegularExpression"). The second form requires that certain special characters that normally have a single \ in front now have a double \\.
The g and i characters at the end of a regular expression ensure a global and case-insensitive match is made—for example, myRegExp = /Pattern/gi;.
As well as specifying actual characters, regular expressions have certain groups of special characters, which allow any of a certain groups of characters, such as digits, words, or non-word characters, to be matched.
Special characters can also be used to specify pattern or character repetition. Additionally we can specify what the pattern boundaries must be, for example at the beginning or end of the string or next to a word or non-word boundary.
Finally we can define groups of characters that can be used later in the regular expression or in the results of using the expression with the replace() method.
We also updated the trivia quiz in this chapter to allow questions to be set that require a text-based response from the user, as well as multiple-choice questions, which we have already seen.
In the next chapter we'll take a look at using and manipulating dates and times using JavaScript, and time conversion between different world time zones. Also covered is how to create a timer that executes code at regular intervals after the page is loaded. We'll be adapting the trivia quiz so that the user can select a time within which it must be completed, for example five questions in one minute.