Regular expressions are objects in JavaScript. For example, if you have an input field that should only allow characters a-z (lower and upper case) and numerical digits, you could use regular expressions to do the input validation as follows:

There are number of ways you can trim strings using javascript. The best way is to prototype the string object, adding a trim method, so you can perform the action by merely calling "string.trim()".

Regular expressions provide a slick way of trimming strings, but at the time of writing regular expression implementations can be buggy in some browsers, and you may find it doesn't always work. This will probably be the standard going forward.

Trimming with Regular Expressions

// Add a function called trim as a method of the prototype
// object of the String constructor.
String.prototype.trim = function() {
// Use a regular expression to replace leading and trailing
// spaces with the empty string
return this.replace(/^(s+)?(.*S)(s+)?$/, '$2');
}

For now, a more reliable way is to just use the substring method and just loop through the string characters. The following three methods provide a left trim, right trim and full trim:

Alternatively, a cleaner approach is to prototype the string object, effectively adding the replaceAll method to the string class. Using the following approach, you can then use this method as you would any other string method, e.g. yourstring.replaceAll('a', 'b');

The onbeforeunload event handler (supported by Internet Explorer 4+ only) can be used to confirm that the user does want to close the browser window or navigate away from the current page. If your event handler returns something, this message will be included in a confirmation which the user must click OK to. If you do not return anything, the event handler is ignored: