SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,820
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)

    a couple js regex questions

    I am quite a novice at javascript, but I do have gained an understanding of OOP from PHP.

    I have seen RegExp() object being used in some script... BUT I also have seen this being used instead: cls=/ain/gi;

    What is the advantage of using an object instead of a simple variable as above?

    and at the risk of answering my own question, is there a way to use a variable INSIDE a regex expression when NOT using the RegExp() object?
    something like this...

    VariableHere="some_sting";
    cls=/(\s|^)VariableHere(\s|$)/gi;


    As always .. advice is appreciated and thanks in advance

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by dresden_phoenix View Post
    I have seen RegExp() object being used in some script... BUT I also have seen this being used instead: cls=/ain/gi;

    What is the advantage of using an object instead of a simple variable as above?
    Using the RegExp constructor creates the same object as using the regular expression literal. The literal form is the preferred technique. Use the RegExp constructor only when the pattern may be variable, or when it's provided from an external source.

    Quote Originally Posted by dresden_phoenix View Post
    and at the risk of answering my own question, is there a way to use a variable INSIDE a regex expression when NOT using the RegExp() object?
    Not unless you want mobs of people screaming "eval is evil!!!" in your ear.

    You'll need the RegExp constructor for that.

    When using the constructor, since normal string escape rules apply, you'll also need to escape occurrences of the backslash.

    Code javascript:
    cls = new RegExp('(\\s|^)' + VariableHere + '(\\s|$)', 'gi');
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,820
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    Thanks Paul! I think I get it now.


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
  •