jQuery Trick #2: Global search flag in Regular Expression

In this post I am going to explain, the usage of the global search flag while working on a Regular Expression. We will find out how this simple trick can help us. By the way, this is my second post in the series of jQuery Tricks .

Issue

Few days back I came across an issue in one of the Q&A site. User who posted the question said that, he wanted to replace duplicate ‘exclamation mark’ (!) from a string like given below.

JS:

var str = 'sample!! dummy!! text!!';
alert(str.replace(/!{2,}/, "!"));

Result:

sample! dummy!! text!!

Expected Result:

sample! dummy! text!

Demo:

Trick

The simple trick here to resolve this issue is to set the global search flag to the Regular Expression, here /!{2,}/ like this /!{2,}/g (note the g flag being added here).

var str = 'sample!! dummy!! text!!';
alert(str.replace(/!{2,}/g, "!"));

The usage of the global search flag g here is that, it looks for one or more exclamation mark (!), and it looks for this combination throughout the string. So, the above code replace all the duplicate instances of the exclamation mark (!) with a single exclamation mark (!) and the result we get is, as expected by the user.

Result:

sample! dummy! text!

Demo:

Note:

So, we saw how this simple trick can save our whole day, energy, resource and in some cases head scratching for hours :P. That’s it! If you have any comments or suggestion about this post, I would really appreciate it.

Happy Coding đŸ™‚

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s