Category Archives: JavaScript

Use Regular Expression in JavaScript

What are Regular Expressions?

Regular Expressions are a powerful and effective way to do searches and replaces in a String. With this feature we can do complex validations in only a few lines of code. However, when dealing with really complex expressions it can be harder to use, specially when we code in different languages, like PHP, JavaScript, ASP.Net, and other.


How to use it on JavaScript?

JavaScript allow us to use Regular Expressions in two different ways. We can do it with a literal expression, or with the RegEx Object. The major difference between this two ways is that with the Object we can change the expression at runtime. However, when we use literal regular expressions we achieve better results, because the literal expressions are compiled at load time and provides better performance.

Using literal declaration:
var re = /protech/i;

Using RegEx Object Constructor:
var re = new RegEx(“protech”,”i”);

In JavaScript we can use regular expression with two different approaches. Using the methods that the String Object provide or the RegEx methods.

RegEx methods:

  • compile – Change the regular expression in runtime
  • exec – Search a string with the regular expression and returns the found values.
  • test – Search a string with the regular expression and returns a boolean true or false indicating if found a match.

String methods:

  • search – Search the String with a regular expression and return the position.
  • match – Search the String with a regular expression and return an array of found values.
  • replace – Replace characters according to the regular expression.
  • split – Split a String according to the regular expression.

In this post i don’t want to explain the regular expression feature neither go much deeper in it’s use in JavaScript. I only want to make reference to the feature and share an interesting experience using it.

Let’s see an example of the use of regular expressions in JavaScript. This code will validate an e-mail in JavaScript using regular expressions. It’s easy to do but has a catch that I’ll show you.

// Three strings to test
var str = “a,b@protech.ws4.org”;
var str2 = “webmaster@Protech.ws4.org”;
var str3 = “a.b”; // These string is for sanity check// Literal declaration of the regular expression

var literal_regexp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;

// RegEx Object Constructor declaration
var object_regexp = new RegExp(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”,”i”);

// Result of the aplications of regular expressions
alert(str.search(literal_regexp)); // Writes -1
alert(str.search(object_regexp)); // Writes 0
alert(object_regexp.test(str)); // Writes true
alert(object_regexp.exec(str)); // Writes a,b@protech.ws4.org,,b,.ws4,.org

alert(str2.search(literal_regexp)); // Writes 0
alert(str2.search(object_regexp)); // Writes 0
alert(object_regexp.test(str2)); // Writes true
alert(object_regexp.exec(str2)); // Writes webmaster@Protech.ws4.org,,.ws4,.org

// With different declarations we achieve different results in the first string.

// Lets make a simples change
var object_regexp2 = new RegExp(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i);

// Result of the aplications of regular expressions
alert(str.search(literal_regexp)); // Writes -1
alert(str.search(object_regexp2)); // Writes -1
alert(object_regexp2.test(str)); // Writes false
alert(object_regexp2.exec(str)); // Writes null

// As we can see be aware when using RegExp Object that the behavior is not the same.

// Sanity check
var slre = /\./;
var sore = new RegExp(“\.”);
alert(str3.search(slre)); // Writes 1
alert(str3.search(sore)); // Writes 0
alert(sore.test(str3)); // Writes true
alert(sore.exec(str3)); // Writes a

Using the RegExp Object, when we try to find a real dot, scaping the dot like we usually do in regular expression, in the String the object assumes like the dot that means, in regular expression, any character

I really don’t know why this happened. If you do please comment this post. However, i think it’s better to use literal declaration.

Like I said, there are many websites explaining regular expressions and it use in JavaScript. Use the following links for further information:

Show PNG transparency in IE6

Every web developer knows that develop cross-browsers web applications is a real pain in the ass. To complicate the things a little bit, the change from IE6 to IE7 bring many differences that turn the develop process harder.

One key limitation in the old Internet Explorer 6 (IE6) is the Portable Network graphics (PNG) transparency problem. In this version of IE, pages that contain PNG images with transparent background are shown wrong. The background of the image is shown gray rather than transparent.

To solve this problem Microsoft recommends that web developers use the AlphaImageLoader filter. This is specific IE CSS filter that can be used with images to show the PNG transparency. The filter can be used as shown below:

<html>
<head>Show PNG transparency in IE6</head>
<body style=”background-color:#FFFFFF;”>
<!– Div that handles the transparent image –>
<div style=”height:400; width:400;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,
src=’image.png’, sizingMethod=scale);” >
</div>
</body>
</html>

AlphaImageLoader has two parameters, the src and the sizingMethod. The first one is used to set the source image file to be filtered and the second one is used to set the sizing behavior that the object and the image have. The sizingMethod can take three values:
crop – Clips the image to fit the dimensions of the object;
image – Default. The object fits the dimensions of the image;
scale – The images changes its size to fill the object;

This CSS filter can be used as an object in JavaScript. This way, there is another property called enabled to set or disable the filter.

Form more information about AlphaImageLoader filter check MSDN website.

Detect cookie support with JavaScript

Cookies, also known as web cookies, HTTP Cookies or just cookies, are a mechanism that allow the store of that in the client’s browser. This information is sent by a server to the web browser and then sent back without change each time the browser access that server. Cookies are used for several purposes such authentication, tracking or just to hold specific information, such users preferences in a web site. The idea and name was inspired in the well-known concept “magic cookie” from UNIX.

This mechanism is so common between developers that most of the times we forget to check the client browser support for them. When we develop an application that uses cookies we must check their support to avoid some errors. This can be done in several ways, such with server side scripting. The code bellow shows a simple way to check cookies support with JavaScript.

<script type=”text/javascript”>
var cookiesON = false;
if (typeof navigator.cookieEnabled==”undefined”)
{
//if other than IE4+ and NS6+
var date = new Date();
document.cookie = “checkCookie=”+date.getTime();
cookiesON = (document.cookie.indexOf(“checkCookie”)!=-1)? true : false
}
else
{
//if IE4+ or NS6+
cookiesON = (navigator.cookieEnabled)? true : false;
}

//Do something
if (cookiesON)
alert(‘Cookies ON’);
else
alert(‘Cookies OFF’);
</script>

One problem that comes with the web development is the need to develop cross-browser applications. This way, in the above code you see two different ways of check cookie support in JavaScript.

  • The first one checks cookies on browsers different from IE4+ and NS6+ by trying to put a dummy value in the cookie and read it. If we could read it, is because cookies are enabled. There is no problem by storing the dummy value because this one is removed when the browser is closed. This is the behavior when isn’t specified a expire date.
  • We could use the same verification for all browsers. However, browsers like IE4+ or NS6+ have the cookie support information built-in with a navigator property “cookieEnabled”.