SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    John 8:24 JREAM's Avatar
    Join Date
    Sep 2007
    Location
    Florida
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex in a variable?

    var x = /[a-z0-9]/;

    possible?

    function this(){
    document.write ([a-z0-9]);
    }

    no?

    What is the trick!

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, it's possible to have a regular expression as a variable.

    Your function won't work, partly because you've named it this, which is a reserved word, and partly because you're not passing a regular expression anywhere. The argument you're using in document.write() is an array containing one element whose value is that of an expression resulting from the calculation a - z0 - 9 (which is undefined in this example).

    If you're trying to write out all the characters that match the regex, then you're barking up the wrong tree. A regex is a pattern which can be used for matching strings, but you can't 'translate' it into anything that would match it. That would be impossible in the general case; what would you expect /^.*foo.*$/ to print, for instance? There are an infinite number of strings matching that pattern.

    The pattern /[a-z0-9]/ matches exactly one out of 36 possible characters. It doesn't represent the string "abcdefghijklmnopqrstuvwxyz0123456789"; it represents a pattern that matches one of those characters.

    If you want to write out the expression pattern, you can use document.write(x.toString()), but I'm not sure that's what you're asking for.
    Birnam wood is come to Dunsinane

  3. #3
    John 8:24 JREAM's Avatar
    Join Date
    Sep 2007
    Location
    Florida
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That makes sense, I realize my question sounds very silly now for applying regex this way. But thats a cool idea you have..


    var arf = new RegExp(/[A-Z]+[a-z]/);
    document.write(arf.toString);

    Render: function toString() { [native code] }

    This is probably a waste of time :P

  4. #4
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    toString is a function/method, I'm sure you know what that is since you have a whole js tutorial on your site - and the way you use it is by adding '()' after the function name which invokes it.

    Code:
    var arf = /[A-Z]+[a-z]/; arf.toString();


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •