JavaScript-RegExp Object.

Posted on 27/09/2009 by

4



What is RegExp?
The RegExp object is basically used to specify what to search for in a text. It is short for Regular Expression. When you search in a text, you can use a pattern to describe what you are searching for. RegExp IS this pattern.. and a simple pattern can be a single character. A more difficult pattern consists of more characters, and can be used for parsing, format checking substituation and much more!!…You can also specify where in the string to search, what type of characters to search for and more.
The RegExp object can also be used to store the search pattern. We define a RegExp object with the new Keyword.

Example:
var patt1=new RegExp (“e”)
This explains the code defines a RegExp object called patt1 with the pattern “e”.

Methods Of RegExp Object.
The RegExp Object has 3 methods: test(), exec() and compile().

Example1: test()
This method searches a string for a specified value. Returns true or False.
Input

<html>
<body>

<script type=”text/javascript”>
var patt1=new RegExp(“e”);

document.write(patt1.test(“The best things in life are free”));
</script>

</body>
</html>

Output

true

Example1:exec()
The exec() method searches a string for a specified value. Returns the text of the found value. If no match is found, it returns null.

Input

<html>
<body>

<script type=”text/javascript”>
var patt1=new RegExp(“e”);

document.write(patt1.exec(“The best things in life are free”));
</script>

</body>
</html>

Output
e

You can add a second parameter to the RegExp object to specify your search. For example: If you want to find all occurrences of a character, you can use “g” parameter (“global”).When using the “g” parameter the exec() and it works like this:

  • Finds the first occurence of “e”, and stores its position
  • If you run exec() again, it starts at the stored position, and finds the next occurence of “e”, and stores its position.
    Example2:exec()Input <html>
    <body><script type=”text/javascript”>
    var patt1=new RegExp(“e”,”g”);do
    {
    result=patt1.exec(“The best things in life are free”);
    document.write(result);
    }
    while (result!=null)
    </script></body>
    </html>Output

    eeeeeenullExample3:compile() The compile() method is used to change the RegExp. compile() can also change both the search pattern, and add or remove the second parameter.Input

    <html>
    <body>

    <script type=”text/javascript”>
    var patt1=new RegExp(“e”);
    document.write(patt1.test(“The best things in life are free”));

    patt1.compile(“d”);

    document.write(patt1.test(“The best things in life are free”));
    </script>

    </body>
    </html>

    Output

    truefalse

    Enjoy!!

    EllaHax

Advertisements
Posted in: Coding, Html, JavaScript