Completely confused! -- Regular Expressions

Discussion in 'JavaScript' started by maximusdm, May 6, 2010.

  1. #1
    From my research we should use Regular Expressions in 2 ways:

    1) Using literal syntax.
    2) When you need to dynamically construct the regular expression, via the RegExp() constructor.

    The literal syntax looks something like: var RegularExpression = /pattern/
    while the RegExp() constructor method looks like var RegularExpression = new RegExp("pattern");

    Well my code NEVER works when I use double quotes. It ONLY works the way I present below:

    var RegExp1 = new RegExp(/^.*$/);
    if (!RegExp1.test(globalValueControl.value))
    {
    //bla bla }

    Also, I got the sample code below and it's using a SINGLE quote:

    var octet = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])';
    var ip = '(?:' + octet + '\\.){3}' + octet;
    var RegExp1 = new RegExp('^' + ip + '$' );

    Not sure how and why that works. My code did not work with double or single quotes, what am I missing here? What is the right process/standard here?

    Thank you
     
    maximusdm, May 6, 2010 IP
  2. arpx

    arpx Peon

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    you can create regex object by both

    var re = new RegExp('.*');
    var re =/.*/;

    the later is better since you must double backslash the first one
    then its just to feed it with a string to execute

    var result = re.exec('Your text');
     
    arpx, May 7, 2010 IP
  3. maximusdm

    maximusdm Peon

    Messages:
    18
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    yes, I understand what you typed but as I mentioned in my first statement, it won't work for me.
    The only way it works is if I use the the RegExp() constructor passing the pattern between "/" which is so weird:

    var RegExp1 = new RegExp(/^.*$/);
    if (!RegExp1.test(globalValueControl.value))
     
    maximusdm, May 7, 2010 IP
  4. unigogo

    unigogo Peon

    Messages:
    286
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    That is because sometimes you need quote the special charectors in your regexp string. Coz I don't know what is exactly your regexp doing for. I suggest a way of debug this kind of problem.

    Add an <textarea id="tmp"> tag in your page. write the regexp string into the textarea. See if it's still your original regexp.
     
    unigogo, May 8, 2010 IP