JavaScript is useful for a lot more than opening pop-ups. If you use HTML forms on your website, and want to make sure that your visitors submit valid data on those forms, you might want to consider using some regular expressions in JavaScript. Alejandro Gervasio explains how, with many excellent examples.
Regular expressions in JavaScript - The replace() method (Page 8 of 9 )
As you might suppose, replace() method replaces matches to a given regular expression with some new string. For a simple example, let�s say we want to replace every newline character (\n) with a break <br /> tag, within a form field used for comments, by formatting the content for proper displaying.
For example:
comment = document.forms[0].comments.value; // assumes that our HTML form the first one present in the document, and it has a field named �comments�
comment = comment.replace(/\n/g, �<br />�);
Pretty simple, right?, The first parameter taken is the regular expression we�re searching for (please note the g modifier indicating that it will do a global search, so it will find all of the occurrences in the string, not just the first). The second argument or parameter is the string with which we want to replace any matches (in this case, the <br /> tag).
The function accepts any string as a parameter, and returns the new string with all of the newline characters replaced by <br /> tags.
In a moment, we�ll see another useful method used with regular expressions: the search() method.
The search() method
The search() method is very similar to the indexOf() method, with the difference being that it takes a regular expression as a parameter instead of a string. Then it searches the string for the first match to the given regular expression and returns an integer that indicates the position in the string (strings in JavaScript are zero-indexed elements, so it would return 0 if the match is at the start of the string, 5 if the match begins with the 5th character in the string, and so on). If no match is found, the method will return �1.
Let�s say we wish to know the location of the first absolute link within a HTML document. We might code something like this:
pos = htmlString.search(/^<a href=�http:\/\/$/i); if ( pos != -1) { alert( �First absolute link found at� + pos +�position.�); } else { alert ( �Absolute links not found�); }
It�s very simple and not quite useful, but good enough for example purposes.
So far, all methods described here work by accepting a regular expression as the parameter. Now, let�s take a detailed look at our final method: test(), which is by far the most used to perform client-side validation when using regular expressions in JavaScript.