Using Regular Expressions in Javascript

Regular expressions can be used to find the patterns in strings. There are lots of  special characters and methods used in regular expressions and each one having separate meaning. For more details about that read here
In this blog am writing about how to use that regular expressions in javascript. Methods that use in regular expressions are exec, test, match, search, replace and split. Also am not going to explain about each methods because the above sun documents will guide you those things clearly.
Lets see an example that will help you to understand clearly.

Example1: Check whether the given string is Numeric or not.

Regular expression  /^[0-9]+$/ is used to find a string is numeric. In this

  • [0-9] – represents numeric digits only allowed.
  • + – matches any number of characters.
  • ^ – matches beginning of the line
  • $ – matches end of the line

test – test the match of a given input string with regular expressions. returns true if it matches correctly otherwise returns false.

function isNumeric(input)
var regexp = /^[0-9]+$/;
if(regexp .test(input))
return true;
return false;

Note : you can also use regular expression /d for matching numeric characters.

Example 2: Replace all occurrences of a string with substring

Suppose if you want to replace all hypen (-) characters with space in input string s = “12-November-2008”
Below code will replace it.

replace – method used to search and replace for a matching string with substring.

regular expression:  /-/g

/- matches the string hypen(-)
/g – matches all occurrences of the string.

var s = “12-November-2008”;
s = s.replace(/-/g,’ ‘);

output : “12 November 2008”

Special Parameters are

/g – enables global matching, in the above example it matches all hypen(-) characters.
/i – makes case insensitive.
/m – multi-line mode


Tags: , , , , , , , , , , , , ,

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: