Regular Expressions

Understanding Regular Expressions
match patterns of characters
    /pattern/modifiers
    
find any of the characters between the brackets
    [abc]
    
find any digit
    [0-9]
    
find any alternative separated by pipe
    (ab|xy)
    
simple example
    <script>
        var pattern = /with an x/;
        // returns true
        alert(pattern.test("I marked the paper with an x."));

        pattern = /with an e/;
        // returns falsee
        alert(pattern.test("I marked the paper with an x."));
    </script>
        
Top

Index

Testing for Matches
    <script>
        var pattern = /.tv/;
        alert(pattern.test("LearnToProgram.tv"));

        // test for either - returns true
        pattern = /(.tv|.com)/;
        alert(pattern.test("LearnToProgram.tv"));

        // returns false
        alert(pattern.test("LearnToProgram.biz"));

        // test for either not being in string - returns true
        pattern = /^(.tv|.com)/;
        alert(pattern.test("LearnToProgram.biz"));

        // test for A in string - returns false
        pattern = /[A]/;
        alert(pattern.test("LearnToProgram.biz"));

        // test for A in string with case insensitive modifier - returns true
        pattern = /[A]/i;
        alert(pattern.test("LearnToProgram.biz"));
    </script>
        
Top

Index

Search and Replace with RegEx
        
    <script>
        /* search */
        var myString = "The quick brown fox jumped over the lazy dogs.";
        // search for particular expression within string - returns -1 as no digits found
        console.log(myString.search(/[0-9]/));
        // returns 10 as location of pattern found (zero-based character index)
        console.log(myString.search(/brown/i));

        var searchFor = prompt("What would you like to search for?");
        // can't use a variable 
        console.log(myString.search(/searchFor/));
        // still fails
        var searchPattern = "/" + searchFor + "/i";
        console.log(myString.search(searchPattern));

        /* replace */
        var number = "203.222.2323";
        // change dots to dashes - only first dot replaced
        var number1 = number.replace(/[.]/, "-");
        console.log(number1);

        // change dots to dashes - use global modifier to replace all
        number1 = number.replace(/[.]/g, "-");
        console.log(number1);
    </script>
    
Top

Index

n4jvp.com