Extracting Strings

String validation isn’t the only useful thing you can do with regular expressions. String extraction is also useful; being able to take just part of a string and manipulate it allows you to have more control over the final result. In Script 8.4, we’ll take a list of names entered in first-name-first order and swap them so that they’re in last-name-first order.

To extract strings:

1.
var re = /\s*\n\s*/;
Here’s a new regular expression, which simply searches for a pattern that consists of any white space \s*, followed by a new line character \n, followed again by any white space \s*.
2.
var nameList = inNameList.split(re);
The string method split() takes the regular expression and applies it to the data entered by the user ...

Get JavaScript and Ajax for the Web: Visual QuickStart Guide, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.