JavaScript Regular Expressions

      No Comments on JavaScript Regular Expressions

JavaScript Regular Expressions are patterns which are used to match combinations in strings.

A regular expressions are used to describe a pattern.
Regular expressions are used for:

  • pattern matching
  • to perform search functions of text
  • to perform replace text functions

JavaScript Regular Expressions are also referred to as objects.

Syntax of creating regular expressions

  /pattern/modifiers;

eg: /scanfcode/g

Creating regExp

Method 1:using literals

 var regx= /ab+c/;

Method 2: Calling constructor

  var regx = new RegExp('ab+c');

JavaScript Regular Expressions -using the match() example:




Here is the code:

<script>
function check_type()
{
  var a=document.getElementById('test_input_reg').value;
if(a.match(/[a-z]/)) 
  {
     alert("Alphabet entered");
  }
 if(a.match(/[0-9]/))
   {
    alert("Number entered");
   }
}
</script>

a.match(/[a-z]/) here a is the variable having value from the input. match() function matches the input value with the pattern passed as argument which is /[a-z]/

Brackets

Brackets are used to specify range.Here are just few

ExpressionDescription
[abc]Find any character between the brackets
[^abc]Find any character NOT between the brackets
[0-9]Find any character between the brackets (any digit)

Methods:

MethodDescription
match()Retrieves the matches when matching a string against a regular expression
exec()Tests for a match in a string. Returns the first match
test()Tests for a match in a string. Returns true or false
toString()Returns the string value of the regular expression

Various modifiers

ModifierUse
i performs case-sensitive matching
g Performs global matching, does not stop on first match
m performs multi-line matching

Leave a Reply

Your email address will not be published. Required fields are marked *