Reg Exp
Web Design
Notes Client
Replace Repeated Words
Although this probably isn't the most useful regular expression in the world, it is a very simple one and really shows some of the power of regular expressions. It will get rid of repeated words in an input field on a web form. (Repeated as in "the the").

Place this function in your JavaScript head area:

function replaceDups(field) {
   field.value = field.value.replace(/\s(\w+\s)\1/, " $1");

Next, pass in a handle to the field field to be updated:


The function does the rest. The function works by looking for a space followed by the group in parentheses repeated (the \1 flag looks for the repeat of the first group of parentheses). The group is one or more of any character followed by a space. So if one or more characters, then a space (which is really a word in lay terms) is immediately repeated, it's replaced. What replaces it? $1 in the replace indicates to use the value remembered from the first parentheses, so the phrase "the the" would be replaced with "the" -- the first instance.