SlightlyLoony
Tera Contributor
Options
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
07-06-2010
05:35 AM
The following little snippet of JavaScript uses the replace() method on a string, but in a way you may not be familiar with. What do you think this script will log if you run it?
var x = "This is a test. This is only a test. If only we had known...";
x = x.replace(/ only (.*?)\./g, " mainly $1.");
gs.log(x);
The correct answer is: "This is a test. This is mainly a test. If mainly we had known..."
Surprised? Here's what's going on:
- The stuff between the slashes (" only (.*?)\.") is a regular expression. There are two kinds of people in the world: those who understand regular expressions, and those who don't. Of course real men understand them. They are JavaScript's most powerful tool for analyzing and manipulating text. They're well worth learning, both for their utility and so that you don't abuse them (because, like any other tool, they can be dangerous if misused).
- The "g" following the regular expression means "global". In a replace method, that means it will replace all occurrences of the matching string.
- The example's regular expression will match any sequence of " only" followed by anything at all, up to the next period. The "anything at all" is captured (that's what the parentheses do). There can be any number of capture groups, but in our case we have just the one. The test text has two matching strings. For the first one, it will capture "a test", for the second "we had known".
- The replacement string (" mainly $1.") replaces the matched strings with " mainly " followed by the captured text from capture group 1 (that's the "$1") followed by a period. In our test case, the string matched in two places. For the first one, the replacement value is " mainly a test.", for the second it's " mainly we had known."
Does the result make more sense now? If not, I prescribe this book.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.