Article

Regular Expressions in JavaScript

Page: 1 2 3 4 5 Next

replace()

As its name would suggest, replace() lets you replace matches to a given regular expression with some new string. Let’s say you were a spelling nut and wanted to enforce the old adage “I before E, except after C” to correct such misspellings as “acheive” and “cieling”. What we’d need is a function that takes a string and performs two search-and-replace operations. The first would replace “cie” with “cei”. Here’s the code:
Get Your Copy of Kevin Yanks Book NOW!
theString = theString.replace(/cie/gi,”cei”);

Simple enough, right? The first parameter is the regular expression that we’re searching for (notice that we’ve set it to “ignore case” and to be “global” so that it finds all occurrences, not just the first), and the second parameter is the string that we want to replace any matches with.

The second replacement is a little more complicated. We want to replace “xei” with “xie” where ‘x’ is any letter except ‘c’. The regular expression to detect instances of “xei” is fairly easy to understand:

/[abd-z]ei/gi

This just detects any letter except ‘c’ (‘a’, ‘b’, and ‘d’ to ‘z’ inclusive), followed by “ei”, and does it in a global, case-insensitive manner.

The complexity comes in defining our replacement string. Obviously, we want to replace the match with “xie”, but the difficulty comes in writing the ‘x’. Remember, we have to replace ‘x’ with whatever letter appears in the matching string. To do this, we need to learn a new trick.

Earlier on, I showed you how parentheses could be used to define a set of alternatives in a regular expression (e.g. ^(ba|na)+$). Well as it turns out, parentheses have another meaning, too. They let us “remember” part of a match, so that we can use it in the replacement string. In this case, we want to remember the portion of the match that corresponds to the [abd-z] in the regular expression. Thus, we surround it with parentheses:

/([abd-z])ei/gi

Now, when specifying the replacement string, we put $1 where we want to insert the portion of the string corresponding to the parenthesised portion of the regular expression. Thus, the code for performing the required substitutions is as follows:

theString = theString.replace(/([abd-z])ei/gi,”$1ie”);

To sum it up, here’s the complete function for performing our auto-correction:

function autoCorrect(theString) {    
 theString = theString.replace(/cie/gi,”cei”);    
 theString = theString.replace(/([abd-z])ei/gi,”$1ie”);    
 return theString;    
}

Before you go and use this function on your page, realize that there are exceptions to the “I before E except after C” rule. Weird, huh?

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links