Using Regular Expression in JavaScript

RegExp is a Regular Expression object in Java Script. RegExp object is useful to search texts in a texts.

The RegExp object contains three member functions:


  1. test()

  2. exec(), and

  3. compile()



The test () method searches a string for with a specified value. It either returns true or false.


var testPattern=new RegExp("kapil");
document.write(testPattern.test("I am kapil dhawan")); //returns true


The exec () method searches a string for a specified value. But, unlike test (), it returns the text of the value found. When no match is found, it returns null.


var execPattern=new RegExp("kapil");
document.write(execPattern.exec("I am kapil Dhawan")); //returns 'kapil'


The compile () method is used to change the RegExp.


var compPattern=new RegExp("kapil");
document.write(compPattern.test("I am kapil dhawan"));//returns true


The other case in this example might be


compPattern.compile("dhawan");
document.write(compPattern.test("I am kapil dhawan")); //returns true


Regular expressions are really powerful in optimizing searches for texts. When used, it obviates the need for a method that has to read the text from the beginning instead of searching for patterns.


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: