Testing for equality of regular expressionsWhich equals operator (== vs ===) should be used in JavaScript comparisons?Regular expressions Equivalencewhat is the purpose of the following expression: (a !== a && b !== b) in angularjs code?jQuery selector regular expressionsWhich equals operator (== vs ===) should be used in JavaScript comparisons?How do you access the matched groups in a JavaScript regular expression?How do you use a variable in a regular expression?How do I test for an empty JavaScript object?Converting user input string to regular expressionJavaScript Date Comparisons Don't EqualTest object equality in CoffeeScript?Two 'equal' javascript objects not equalWhys is [“text”] == [“text”] false?

In Avengers 1, why does Thanos need Loki?

Why do we use caret (^) as the symbol for ctrl/control?

If your medical expenses exceed your income does the IRS pay you?

Multi-channel audio upsampling interpolation

How long would it take for people to notice a mass disappearance?

Does a card have a keyword if it has the same effect as said keyword?

Can my company stop me from working overtime?

Upside-Down Pyramid Addition...REVERSED!

What is the name of this hexagon/pentagon polyhedron?

Why do money exchangers give different rates to different bills?

Why wasn't the Night King naked in S08E03?

Position of past participle and extent of the Verbklammer

Expressing 'our' for objects belonging to our apartment

Why are prions in animal diets not destroyed by the digestive system?

Using field size much larger than necessary

Why was the battle set up *outside* Winterfell?

How to apply Differences on part of list and keep the rest?

What is the most remote airport from the center of the city it supposedly serves?

Why isn't nylon as strong as kevlar?

Can Infinity Stones be retrieved more than once?

Are there any Final Fantasy Spirits in Super Smash Bros Ultimate?

I'm in your subnets, golfing your code

Purpose of のは in this sentence?

Missing Piece of Pie - Can you find it?



Testing for equality of regular expressions


Which equals operator (== vs ===) should be used in JavaScript comparisons?Regular expressions Equivalencewhat is the purpose of the following expression: (a !== a && b !== b) in angularjs code?jQuery selector regular expressionsWhich equals operator (== vs ===) should be used in JavaScript comparisons?How do you access the matched groups in a JavaScript regular expression?How do you use a variable in a regular expression?How do I test for an empty JavaScript object?Converting user input string to regular expressionJavaScript Date Comparisons Don't EqualTest object equality in CoffeeScript?Two 'equal' javascript objects not equalWhys is [“text”] == [“text”] false?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








11















I was surprised to see that



/a/ === /a/


evaluates to false in JavaScript. Reading through the specs:




Two regular expression literals in a program evaluate to regular
expression objects that never compare as === to each other even if the
two literals' contents are identical.




Since === cannot be used to test for equality, how can equality of regular expressions be tested in JavaScript?










share|improve this question






















  • Go through this JavaScript === vs == : Does it matter which “equal” operator I use?

    – Siva Charan
    May 27 '12 at 19:24






  • 4





    You're talking about JavaScript, the language in which [] == [] evaluates to False.

    – Tyler Crompton
    May 27 '12 at 19:25







  • 3





    @SivaCharan how is that useful?

    – Matt Ball
    May 27 '12 at 19:25






  • 3





    @TylerCrompton: don't forget [] == [].length. This question might answer the original question, or at least nudge OP in the right direction.

    – DCoder
    May 27 '12 at 19:28







  • 1





    There's nothing special going on here - this is expected and logical behaviour. RegExp is not a special object, like strings, objects, and arrays - you wouldn't expect new MyClass(x) === new MyClass(x) to be true either.

    – Eric
    May 27 '12 at 19:32


















11















I was surprised to see that



/a/ === /a/


evaluates to false in JavaScript. Reading through the specs:




Two regular expression literals in a program evaluate to regular
expression objects that never compare as === to each other even if the
two literals' contents are identical.




Since === cannot be used to test for equality, how can equality of regular expressions be tested in JavaScript?










share|improve this question






















  • Go through this JavaScript === vs == : Does it matter which “equal” operator I use?

    – Siva Charan
    May 27 '12 at 19:24






  • 4





    You're talking about JavaScript, the language in which [] == [] evaluates to False.

    – Tyler Crompton
    May 27 '12 at 19:25







  • 3





    @SivaCharan how is that useful?

    – Matt Ball
    May 27 '12 at 19:25






  • 3





    @TylerCrompton: don't forget [] == [].length. This question might answer the original question, or at least nudge OP in the right direction.

    – DCoder
    May 27 '12 at 19:28







  • 1





    There's nothing special going on here - this is expected and logical behaviour. RegExp is not a special object, like strings, objects, and arrays - you wouldn't expect new MyClass(x) === new MyClass(x) to be true either.

    – Eric
    May 27 '12 at 19:32














11












11








11


1






I was surprised to see that



/a/ === /a/


evaluates to false in JavaScript. Reading through the specs:




Two regular expression literals in a program evaluate to regular
expression objects that never compare as === to each other even if the
two literals' contents are identical.




Since === cannot be used to test for equality, how can equality of regular expressions be tested in JavaScript?










share|improve this question














I was surprised to see that



/a/ === /a/


evaluates to false in JavaScript. Reading through the specs:




Two regular expression literals in a program evaluate to regular
expression objects that never compare as === to each other even if the
two literals' contents are identical.




Since === cannot be used to test for equality, how can equality of regular expressions be tested in JavaScript?







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 27 '12 at 19:19









RandomblueRandomblue

37.1k120293507




37.1k120293507












  • Go through this JavaScript === vs == : Does it matter which “equal” operator I use?

    – Siva Charan
    May 27 '12 at 19:24






  • 4





    You're talking about JavaScript, the language in which [] == [] evaluates to False.

    – Tyler Crompton
    May 27 '12 at 19:25







  • 3





    @SivaCharan how is that useful?

    – Matt Ball
    May 27 '12 at 19:25






  • 3





    @TylerCrompton: don't forget [] == [].length. This question might answer the original question, or at least nudge OP in the right direction.

    – DCoder
    May 27 '12 at 19:28







  • 1





    There's nothing special going on here - this is expected and logical behaviour. RegExp is not a special object, like strings, objects, and arrays - you wouldn't expect new MyClass(x) === new MyClass(x) to be true either.

    – Eric
    May 27 '12 at 19:32


















  • Go through this JavaScript === vs == : Does it matter which “equal” operator I use?

    – Siva Charan
    May 27 '12 at 19:24






  • 4





    You're talking about JavaScript, the language in which [] == [] evaluates to False.

    – Tyler Crompton
    May 27 '12 at 19:25







  • 3





    @SivaCharan how is that useful?

    – Matt Ball
    May 27 '12 at 19:25






  • 3





    @TylerCrompton: don't forget [] == [].length. This question might answer the original question, or at least nudge OP in the right direction.

    – DCoder
    May 27 '12 at 19:28







  • 1





    There's nothing special going on here - this is expected and logical behaviour. RegExp is not a special object, like strings, objects, and arrays - you wouldn't expect new MyClass(x) === new MyClass(x) to be true either.

    – Eric
    May 27 '12 at 19:32

















Go through this JavaScript === vs == : Does it matter which “equal” operator I use?

– Siva Charan
May 27 '12 at 19:24





Go through this JavaScript === vs == : Does it matter which “equal” operator I use?

– Siva Charan
May 27 '12 at 19:24




4




4





You're talking about JavaScript, the language in which [] == [] evaluates to False.

– Tyler Crompton
May 27 '12 at 19:25






You're talking about JavaScript, the language in which [] == [] evaluates to False.

– Tyler Crompton
May 27 '12 at 19:25





3




3





@SivaCharan how is that useful?

– Matt Ball
May 27 '12 at 19:25





@SivaCharan how is that useful?

– Matt Ball
May 27 '12 at 19:25




3




3





@TylerCrompton: don't forget [] == [].length. This question might answer the original question, or at least nudge OP in the right direction.

– DCoder
May 27 '12 at 19:28






@TylerCrompton: don't forget [] == [].length. This question might answer the original question, or at least nudge OP in the right direction.

– DCoder
May 27 '12 at 19:28





1




1





There's nothing special going on here - this is expected and logical behaviour. RegExp is not a special object, like strings, objects, and arrays - you wouldn't expect new MyClass(x) === new MyClass(x) to be true either.

– Eric
May 27 '12 at 19:32






There's nothing special going on here - this is expected and logical behaviour. RegExp is not a special object, like strings, objects, and arrays - you wouldn't expect new MyClass(x) === new MyClass(x) to be true either.

– Eric
May 27 '12 at 19:32













4 Answers
4






active

oldest

votes


















4














Here's a function that fully tests all the relevant regex properties and makes sure it's the right type of object:



function regexSame(r1, r2) 
if (r1 instanceof RegExp && r2 instanceof RegExp)
var props = ["global", "multiline", "ignoreCase", "source", "dotAll", "sticky", "unicode"];
for (var i = 0; i < props.length; i++)
var prop = props[i];
if (r1[prop] !== r2[prop])
return false;


return true;

return false;




And, since flags sometimes get added to the regex object with new features (as has happened since this original answer in 2012 - though the above code has been updated as of 2019), here's a version that is a bit more future proof on future flags being added since it compares whatever flags are there rather than looking for a specific set of flags. It sorts the flags before comparing to allow for minor differences in how the regex was specified that wouldn't not actually change functionality.



function regexSame(r1, r2) 
return r1 instanceof RegExp &&
r2 instanceof RegExp &&
r1.source === r2.source &&
r1.flags.split("").sort().join("") === r2.flags.split("").sort().join("");






share|improve this answer

























  • You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

    – Donald Duck
    Mar 22 at 21:42











  • @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

    – jfriend00
    Mar 22 at 21:54






  • 1





    @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

    – jfriend00
    Mar 23 at 0:27


















17














Here's a case that even covers ordering of flags.



function regexEqual(x, y) 
return (x instanceof RegExp) && (y instanceof RegExp) &&
(x.source === y.source) && (x.global === y.global) &&
(x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);



Tests:



regexEqual(/a/, /a/) // true
regexEqual(/a/gi, /a/ig) // also true.
regeXEqual(/a/, /b/) // false





share|improve this answer

























  • Isn't that the same as calling .toString()?

    – Eric
    May 27 '12 at 19:29






  • 2





    @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

    – Arka
    May 27 '12 at 19:31







  • 1





    Very nice. I didn't know about .source & co. +1

    – Matt Ball
    May 27 '12 at 19:31











  • @JohnathonArka: Ah, hadn't thought about order of flags.

    – Eric
    May 27 '12 at 22:34






  • 1





    this is a very compact and readable solution - nice!

    – killthrush
    Oct 9 '16 at 14:26


















2














You can check the types with typeof, then toString() both regexes and compare those. It won't cover cases with equivalent flags, such as /a/gi and /a/ig, though.



function regexEquals(a, b)



Unfortunately there's no more-specific type from typeof, so if you really want to make sure they're regexes (or regex-like) you could do something along these lines:



RegExp.prototype.regexEquals = function (other)

return (typeof other.regexEquals === 'function')
&& (this.toString() === other.toString());



Then:



/a/.regexEquals(/a/); // true
/a/.regexEquals(/b/); // false





share|improve this answer

























  • You can also use x instanceof RegExp to check if x is a regex.

    – Donald Duck
    Mar 22 at 21:43


















1














Compare them using toString(), and check their type too:



var a = /a/,
b = /a/;

a.toString() === b.toString() && typeof(a) === typeof(b) //true

var c = /a/,
d = /b/;

c.toString() === d.toString() && typeof(c) === typeof(d) //false





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10776600%2ftesting-for-equality-of-regular-expressions%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    Here's a function that fully tests all the relevant regex properties and makes sure it's the right type of object:



    function regexSame(r1, r2) 
    if (r1 instanceof RegExp && r2 instanceof RegExp)
    var props = ["global", "multiline", "ignoreCase", "source", "dotAll", "sticky", "unicode"];
    for (var i = 0; i < props.length; i++)
    var prop = props[i];
    if (r1[prop] !== r2[prop])
    return false;


    return true;

    return false;




    And, since flags sometimes get added to the regex object with new features (as has happened since this original answer in 2012 - though the above code has been updated as of 2019), here's a version that is a bit more future proof on future flags being added since it compares whatever flags are there rather than looking for a specific set of flags. It sorts the flags before comparing to allow for minor differences in how the regex was specified that wouldn't not actually change functionality.



    function regexSame(r1, r2) 
    return r1 instanceof RegExp &&
    r2 instanceof RegExp &&
    r1.source === r2.source &&
    r1.flags.split("").sort().join("") === r2.flags.split("").sort().join("");






    share|improve this answer

























    • You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

      – Donald Duck
      Mar 22 at 21:42











    • @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

      – jfriend00
      Mar 22 at 21:54






    • 1





      @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

      – jfriend00
      Mar 23 at 0:27















    4














    Here's a function that fully tests all the relevant regex properties and makes sure it's the right type of object:



    function regexSame(r1, r2) 
    if (r1 instanceof RegExp && r2 instanceof RegExp)
    var props = ["global", "multiline", "ignoreCase", "source", "dotAll", "sticky", "unicode"];
    for (var i = 0; i < props.length; i++)
    var prop = props[i];
    if (r1[prop] !== r2[prop])
    return false;


    return true;

    return false;




    And, since flags sometimes get added to the regex object with new features (as has happened since this original answer in 2012 - though the above code has been updated as of 2019), here's a version that is a bit more future proof on future flags being added since it compares whatever flags are there rather than looking for a specific set of flags. It sorts the flags before comparing to allow for minor differences in how the regex was specified that wouldn't not actually change functionality.



    function regexSame(r1, r2) 
    return r1 instanceof RegExp &&
    r2 instanceof RegExp &&
    r1.source === r2.source &&
    r1.flags.split("").sort().join("") === r2.flags.split("").sort().join("");






    share|improve this answer

























    • You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

      – Donald Duck
      Mar 22 at 21:42











    • @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

      – jfriend00
      Mar 22 at 21:54






    • 1





      @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

      – jfriend00
      Mar 23 at 0:27













    4












    4








    4







    Here's a function that fully tests all the relevant regex properties and makes sure it's the right type of object:



    function regexSame(r1, r2) 
    if (r1 instanceof RegExp && r2 instanceof RegExp)
    var props = ["global", "multiline", "ignoreCase", "source", "dotAll", "sticky", "unicode"];
    for (var i = 0; i < props.length; i++)
    var prop = props[i];
    if (r1[prop] !== r2[prop])
    return false;


    return true;

    return false;




    And, since flags sometimes get added to the regex object with new features (as has happened since this original answer in 2012 - though the above code has been updated as of 2019), here's a version that is a bit more future proof on future flags being added since it compares whatever flags are there rather than looking for a specific set of flags. It sorts the flags before comparing to allow for minor differences in how the regex was specified that wouldn't not actually change functionality.



    function regexSame(r1, r2) 
    return r1 instanceof RegExp &&
    r2 instanceof RegExp &&
    r1.source === r2.source &&
    r1.flags.split("").sort().join("") === r2.flags.split("").sort().join("");






    share|improve this answer















    Here's a function that fully tests all the relevant regex properties and makes sure it's the right type of object:



    function regexSame(r1, r2) 
    if (r1 instanceof RegExp && r2 instanceof RegExp)
    var props = ["global", "multiline", "ignoreCase", "source", "dotAll", "sticky", "unicode"];
    for (var i = 0; i < props.length; i++)
    var prop = props[i];
    if (r1[prop] !== r2[prop])
    return false;


    return true;

    return false;




    And, since flags sometimes get added to the regex object with new features (as has happened since this original answer in 2012 - though the above code has been updated as of 2019), here's a version that is a bit more future proof on future flags being added since it compares whatever flags are there rather than looking for a specific set of flags. It sorts the flags before comparing to allow for minor differences in how the regex was specified that wouldn't not actually change functionality.



    function regexSame(r1, r2) 
    return r1 instanceof RegExp &&
    r2 instanceof RegExp &&
    r1.source === r2.source &&
    r1.flags.split("").sort().join("") === r2.flags.split("").sort().join("");







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 23 at 0:26

























    answered May 27 '12 at 19:36









    jfriend00jfriend00

    445k56584630




    445k56584630












    • You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

      – Donald Duck
      Mar 22 at 21:42











    • @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

      – jfriend00
      Mar 22 at 21:54






    • 1





      @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

      – jfriend00
      Mar 23 at 0:27

















    • You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

      – Donald Duck
      Mar 22 at 21:42











    • @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

      – jfriend00
      Mar 22 at 21:54






    • 1





      @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

      – jfriend00
      Mar 23 at 0:27
















    You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

    – Donald Duck
    Mar 22 at 21:42





    You haven't checked all flags, only g, i and m. For example, with your function, regexSame(/a/s, /a/) would return true. You also need to check the dotAll (s), unicode (u) and sticky (y) properties. You can find a complete list of flags here.

    – Donald Duck
    Mar 22 at 21:42













    @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

    – jfriend00
    Mar 22 at 21:54





    @DonaldDuck - OK, I added those properties. I'm not sure those properties were documented (or perhaps even supported) back in 2012 when this answer was written. Anyway, it's been updated now.

    – jfriend00
    Mar 22 at 21:54




    1




    1





    @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

    – jfriend00
    Mar 23 at 0:27





    @DonaldDuck - I added a bit more future proof version that will continue to work when new flags are added in the future.

    – jfriend00
    Mar 23 at 0:27













    17














    Here's a case that even covers ordering of flags.



    function regexEqual(x, y) 
    return (x instanceof RegExp) && (y instanceof RegExp) &&
    (x.source === y.source) && (x.global === y.global) &&
    (x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);



    Tests:



    regexEqual(/a/, /a/) // true
    regexEqual(/a/gi, /a/ig) // also true.
    regeXEqual(/a/, /b/) // false





    share|improve this answer

























    • Isn't that the same as calling .toString()?

      – Eric
      May 27 '12 at 19:29






    • 2





      @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

      – Arka
      May 27 '12 at 19:31







    • 1





      Very nice. I didn't know about .source & co. +1

      – Matt Ball
      May 27 '12 at 19:31











    • @JohnathonArka: Ah, hadn't thought about order of flags.

      – Eric
      May 27 '12 at 22:34






    • 1





      this is a very compact and readable solution - nice!

      – killthrush
      Oct 9 '16 at 14:26















    17














    Here's a case that even covers ordering of flags.



    function regexEqual(x, y) 
    return (x instanceof RegExp) && (y instanceof RegExp) &&
    (x.source === y.source) && (x.global === y.global) &&
    (x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);



    Tests:



    regexEqual(/a/, /a/) // true
    regexEqual(/a/gi, /a/ig) // also true.
    regeXEqual(/a/, /b/) // false





    share|improve this answer

























    • Isn't that the same as calling .toString()?

      – Eric
      May 27 '12 at 19:29






    • 2





      @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

      – Arka
      May 27 '12 at 19:31







    • 1





      Very nice. I didn't know about .source & co. +1

      – Matt Ball
      May 27 '12 at 19:31











    • @JohnathonArka: Ah, hadn't thought about order of flags.

      – Eric
      May 27 '12 at 22:34






    • 1





      this is a very compact and readable solution - nice!

      – killthrush
      Oct 9 '16 at 14:26













    17












    17








    17







    Here's a case that even covers ordering of flags.



    function regexEqual(x, y) 
    return (x instanceof RegExp) && (y instanceof RegExp) &&
    (x.source === y.source) && (x.global === y.global) &&
    (x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);



    Tests:



    regexEqual(/a/, /a/) // true
    regexEqual(/a/gi, /a/ig) // also true.
    regeXEqual(/a/, /b/) // false





    share|improve this answer















    Here's a case that even covers ordering of flags.



    function regexEqual(x, y) 
    return (x instanceof RegExp) && (y instanceof RegExp) &&
    (x.source === y.source) && (x.global === y.global) &&
    (x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);



    Tests:



    regexEqual(/a/, /a/) // true
    regexEqual(/a/gi, /a/ig) // also true.
    regeXEqual(/a/, /b/) // false






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 27 '12 at 19:56









    Bart Kiers

    134k29246250




    134k29246250










    answered May 27 '12 at 19:28









    ArkaArka

    72737




    72737












    • Isn't that the same as calling .toString()?

      – Eric
      May 27 '12 at 19:29






    • 2





      @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

      – Arka
      May 27 '12 at 19:31







    • 1





      Very nice. I didn't know about .source & co. +1

      – Matt Ball
      May 27 '12 at 19:31











    • @JohnathonArka: Ah, hadn't thought about order of flags.

      – Eric
      May 27 '12 at 22:34






    • 1





      this is a very compact and readable solution - nice!

      – killthrush
      Oct 9 '16 at 14:26

















    • Isn't that the same as calling .toString()?

      – Eric
      May 27 '12 at 19:29






    • 2





      @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

      – Arka
      May 27 '12 at 19:31







    • 1





      Very nice. I didn't know about .source & co. +1

      – Matt Ball
      May 27 '12 at 19:31











    • @JohnathonArka: Ah, hadn't thought about order of flags.

      – Eric
      May 27 '12 at 22:34






    • 1





      this is a very compact and readable solution - nice!

      – killthrush
      Oct 9 '16 at 14:26
















    Isn't that the same as calling .toString()?

    – Eric
    May 27 '12 at 19:29





    Isn't that the same as calling .toString()?

    – Eric
    May 27 '12 at 19:29




    2




    2





    @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

    – Arka
    May 27 '12 at 19:31






    @Eric: No. .toString() returns the exact thing you put in. This uses a predefined order of flags to make sure that /a/gi === /a/ig.

    – Arka
    May 27 '12 at 19:31





    1




    1





    Very nice. I didn't know about .source & co. +1

    – Matt Ball
    May 27 '12 at 19:31





    Very nice. I didn't know about .source & co. +1

    – Matt Ball
    May 27 '12 at 19:31













    @JohnathonArka: Ah, hadn't thought about order of flags.

    – Eric
    May 27 '12 at 22:34





    @JohnathonArka: Ah, hadn't thought about order of flags.

    – Eric
    May 27 '12 at 22:34




    1




    1





    this is a very compact and readable solution - nice!

    – killthrush
    Oct 9 '16 at 14:26





    this is a very compact and readable solution - nice!

    – killthrush
    Oct 9 '16 at 14:26











    2














    You can check the types with typeof, then toString() both regexes and compare those. It won't cover cases with equivalent flags, such as /a/gi and /a/ig, though.



    function regexEquals(a, b)



    Unfortunately there's no more-specific type from typeof, so if you really want to make sure they're regexes (or regex-like) you could do something along these lines:



    RegExp.prototype.regexEquals = function (other)

    return (typeof other.regexEquals === 'function')
    && (this.toString() === other.toString());



    Then:



    /a/.regexEquals(/a/); // true
    /a/.regexEquals(/b/); // false





    share|improve this answer

























    • You can also use x instanceof RegExp to check if x is a regex.

      – Donald Duck
      Mar 22 at 21:43















    2














    You can check the types with typeof, then toString() both regexes and compare those. It won't cover cases with equivalent flags, such as /a/gi and /a/ig, though.



    function regexEquals(a, b)



    Unfortunately there's no more-specific type from typeof, so if you really want to make sure they're regexes (or regex-like) you could do something along these lines:



    RegExp.prototype.regexEquals = function (other)

    return (typeof other.regexEquals === 'function')
    && (this.toString() === other.toString());



    Then:



    /a/.regexEquals(/a/); // true
    /a/.regexEquals(/b/); // false





    share|improve this answer

























    • You can also use x instanceof RegExp to check if x is a regex.

      – Donald Duck
      Mar 22 at 21:43













    2












    2








    2







    You can check the types with typeof, then toString() both regexes and compare those. It won't cover cases with equivalent flags, such as /a/gi and /a/ig, though.



    function regexEquals(a, b)



    Unfortunately there's no more-specific type from typeof, so if you really want to make sure they're regexes (or regex-like) you could do something along these lines:



    RegExp.prototype.regexEquals = function (other)

    return (typeof other.regexEquals === 'function')
    && (this.toString() === other.toString());



    Then:



    /a/.regexEquals(/a/); // true
    /a/.regexEquals(/b/); // false





    share|improve this answer















    You can check the types with typeof, then toString() both regexes and compare those. It won't cover cases with equivalent flags, such as /a/gi and /a/ig, though.



    function regexEquals(a, b)



    Unfortunately there's no more-specific type from typeof, so if you really want to make sure they're regexes (or regex-like) you could do something along these lines:



    RegExp.prototype.regexEquals = function (other)

    return (typeof other.regexEquals === 'function')
    && (this.toString() === other.toString());



    Then:



    /a/.regexEquals(/a/); // true
    /a/.regexEquals(/b/); // false






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 27 '12 at 19:30

























    answered May 27 '12 at 19:22









    Matt BallMatt Ball

    285k76561639




    285k76561639












    • You can also use x instanceof RegExp to check if x is a regex.

      – Donald Duck
      Mar 22 at 21:43

















    • You can also use x instanceof RegExp to check if x is a regex.

      – Donald Duck
      Mar 22 at 21:43
















    You can also use x instanceof RegExp to check if x is a regex.

    – Donald Duck
    Mar 22 at 21:43





    You can also use x instanceof RegExp to check if x is a regex.

    – Donald Duck
    Mar 22 at 21:43











    1














    Compare them using toString(), and check their type too:



    var a = /a/,
    b = /a/;

    a.toString() === b.toString() && typeof(a) === typeof(b) //true

    var c = /a/,
    d = /b/;

    c.toString() === d.toString() && typeof(c) === typeof(d) //false





    share|improve this answer



























      1














      Compare them using toString(), and check their type too:



      var a = /a/,
      b = /a/;

      a.toString() === b.toString() && typeof(a) === typeof(b) //true

      var c = /a/,
      d = /b/;

      c.toString() === d.toString() && typeof(c) === typeof(d) //false





      share|improve this answer

























        1












        1








        1







        Compare them using toString(), and check their type too:



        var a = /a/,
        b = /a/;

        a.toString() === b.toString() && typeof(a) === typeof(b) //true

        var c = /a/,
        d = /b/;

        c.toString() === d.toString() && typeof(c) === typeof(d) //false





        share|improve this answer













        Compare them using toString(), and check their type too:



        var a = /a/,
        b = /a/;

        a.toString() === b.toString() && typeof(a) === typeof(b) //true

        var c = /a/,
        d = /b/;

        c.toString() === d.toString() && typeof(c) === typeof(d) //false






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered May 27 '12 at 19:24









        Derek 朕會功夫Derek 朕會功夫

        62.9k37142193




        62.9k37142193



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10776600%2ftesting-for-equality-of-regular-expressions%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해