Javascript Regex: How to put a variable inside a regular expression?











up vote
146
down vote

favorite
23












So for example:



function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}


But this is of course not working :)
Is there any way to do this?










share|improve this question




















  • 9




    Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking.
    – Tim Pietzcker
    Oct 27 '10 at 6:23






  • 1




    what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question).
    – Eduard
    Oct 17 '17 at 13:12















up vote
146
down vote

favorite
23












So for example:



function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}


But this is of course not working :)
Is there any way to do this?










share|improve this question




















  • 9




    Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking.
    – Tim Pietzcker
    Oct 27 '10 at 6:23






  • 1




    what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question).
    – Eduard
    Oct 17 '17 at 13:12













up vote
146
down vote

favorite
23









up vote
146
down vote

favorite
23






23





So for example:



function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}


But this is of course not working :)
Is there any way to do this?










share|improve this question















So for example:



function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}


But this is of course not working :)
Is there any way to do this?







javascript regex variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 8 '13 at 22:55









Josh Crozier

152k35268221




152k35268221










asked Oct 27 '10 at 0:30









Adam

20.4k52121187




20.4k52121187








  • 9




    Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking.
    – Tim Pietzcker
    Oct 27 '10 at 6:23






  • 1




    what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question).
    – Eduard
    Oct 17 '17 at 13:12














  • 9




    Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking.
    – Tim Pietzcker
    Oct 27 '10 at 6:23






  • 1




    what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question).
    – Eduard
    Oct 17 '17 at 13:12








9




9




Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking.
– Tim Pietzcker
Oct 27 '10 at 6:23




Be aware that if you let the user supply this variable, it's easy for a malicious user to crash your application via catastrophic backtracking.
– Tim Pietzcker
Oct 27 '10 at 6:23




1




1




what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question).
– Eduard
Oct 17 '17 at 13:12




what is "ReGeX"? is it a variable name? it makes answers confusing by implying that it is a part of RegExp construction (in case a reader did not see those weird characters in the question).
– Eduard
Oct 17 '17 at 13:12












7 Answers
7






active

oldest

votes

















up vote
208
down vote



accepted










var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");


Update



Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)






share|improve this answer



















  • 5




    Make sure to escape your string! See @zzzzBov answer
    – jtpereyda
    Oct 6 '15 at 21:18










  • This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
    – Kirankumar Dafda
    Jun 10 '16 at 8:30








  • 6




    One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
    – Ali
    Jan 16 '17 at 14:46








  • 1




    How about the /g?
    – Elgs Qian Chen
    Mar 8 '17 at 3:27


















up vote
67
down vote













You can use the RegExp object:



var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);


Then you can construct regexstring in any way you want.



You can read more about it here.






share|improve this answer

















  • 5




    +1 for the full sample, RegExp params, and link.
    – Jason McCreary
    Oct 27 '10 at 0:45












  • This does not work for me on chrome. :(
    – Ankit Tanna
    May 8 '15 at 9:15










  • var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
    – Ankit Tanna
    May 8 '15 at 9:19




















up vote
28
down vote













To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.



function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}


of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:



function regexEscape(str) {
return str.replace(/[-/\^$*+?.()|[]{}]/g, '\$&')
}

function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}





share|improve this answer























  • The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
    – Michael Rader
    Dec 30 '16 at 1:47








  • 1




    @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
    – zzzzBov
    Dec 30 '16 at 3:49










  • lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
    – Michael Rader
    Dec 30 '16 at 4:43


















up vote
6
down vote













You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.



You can also use RegExp constructor to pass flags in (see the docs).






share|improve this answer




























    up vote
    3
    down vote













    if you're using es6 template literals are an option...



    string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")





    share|improve this answer






























      up vote
      2
      down vote













      accepted answer doesn't work for me and doesn't follow MDN examples



      see the 'Description' section in above link



      I'd go with the following it's working for me:



      let stringThatIsGoingToChange = 'findMe';
      let flagsYouWant = 'gi' //simple string with flags
      let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

      // that makes dynamicRegExp = /findMe/gi





      share|improve this answer























      • It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
        – HelloWorldPeace
        Jun 23 at 19:38












      • flagsYouWant is a string, not a variable, so that won't work
        – macasas
        Sep 14 at 11:24










      • @macasas right you are i think i fixed thanks!
        – Timothy Mitchell
        Oct 4 at 15:40


















      up vote
      1
      down vote













      Here's an pretty useless function that return values wrapped by specific characters. :)



      jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/



      function getValsWrappedIn(str,c1,c2){
      var rg = new RegExp("(?<=\"+c1+")(.*?)(?=\"+c2+")","g");
      return str.match(rg);
      }

      var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
      var results = getValsWrappedIn(exampleStr,"(",")")

      // Will return array ["5","19","thingy"]
      console.log(results)





      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',
        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%2f4029109%2fjavascript-regex-how-to-put-a-variable-inside-a-regular-expression%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        7 Answers
        7






        active

        oldest

        votes








        7 Answers
        7






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        208
        down vote



        accepted










        var regex = new RegExp("ReGeX" + testVar + "ReGeX");
        ...
        string.replace(regex, "replacement");


        Update



        Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)






        share|improve this answer



















        • 5




          Make sure to escape your string! See @zzzzBov answer
          – jtpereyda
          Oct 6 '15 at 21:18










        • This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
          – Kirankumar Dafda
          Jun 10 '16 at 8:30








        • 6




          One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
          – Ali
          Jan 16 '17 at 14:46








        • 1




          How about the /g?
          – Elgs Qian Chen
          Mar 8 '17 at 3:27















        up vote
        208
        down vote



        accepted










        var regex = new RegExp("ReGeX" + testVar + "ReGeX");
        ...
        string.replace(regex, "replacement");


        Update



        Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)






        share|improve this answer



















        • 5




          Make sure to escape your string! See @zzzzBov answer
          – jtpereyda
          Oct 6 '15 at 21:18










        • This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
          – Kirankumar Dafda
          Jun 10 '16 at 8:30








        • 6




          One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
          – Ali
          Jan 16 '17 at 14:46








        • 1




          How about the /g?
          – Elgs Qian Chen
          Mar 8 '17 at 3:27













        up vote
        208
        down vote



        accepted







        up vote
        208
        down vote



        accepted






        var regex = new RegExp("ReGeX" + testVar + "ReGeX");
        ...
        string.replace(regex, "replacement");


        Update



        Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)






        share|improve this answer














        var regex = new RegExp("ReGeX" + testVar + "ReGeX");
        ...
        string.replace(regex, "replacement");


        Update



        Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 23 '17 at 11:55









        Community

        11




        11










        answered Oct 27 '10 at 0:33









        Jason McCreary

        56.4k19104152




        56.4k19104152








        • 5




          Make sure to escape your string! See @zzzzBov answer
          – jtpereyda
          Oct 6 '15 at 21:18










        • This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
          – Kirankumar Dafda
          Jun 10 '16 at 8:30








        • 6




          One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
          – Ali
          Jan 16 '17 at 14:46








        • 1




          How about the /g?
          – Elgs Qian Chen
          Mar 8 '17 at 3:27














        • 5




          Make sure to escape your string! See @zzzzBov answer
          – jtpereyda
          Oct 6 '15 at 21:18










        • This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
          – Kirankumar Dafda
          Jun 10 '16 at 8:30








        • 6




          One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
          – Ali
          Jan 16 '17 at 14:46








        • 1




          How about the /g?
          – Elgs Qian Chen
          Mar 8 '17 at 3:27








        5




        5




        Make sure to escape your string! See @zzzzBov answer
        – jtpereyda
        Oct 6 '15 at 21:18




        Make sure to escape your string! See @zzzzBov answer
        – jtpereyda
        Oct 6 '15 at 21:18












        This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
        – Kirankumar Dafda
        Jun 10 '16 at 8:30






        This is not working in my case, can you please have a look this jsfiddle and let me know if what i have to do if I want to set a country code dynamic into regex expression
        – Kirankumar Dafda
        Jun 10 '16 at 8:30






        6




        6




        One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
        – Ali
        Jan 16 '17 at 14:46






        One important thing to remember is that in regular strings the character needs to be escaped while in the regex literal (usually) the / character needs to be escaped. So /w+//i becomes new RegExp("\w+/", "i")
        – Ali
        Jan 16 '17 at 14:46






        1




        1




        How about the /g?
        – Elgs Qian Chen
        Mar 8 '17 at 3:27




        How about the /g?
        – Elgs Qian Chen
        Mar 8 '17 at 3:27












        up vote
        67
        down vote













        You can use the RegExp object:



        var regexstring = "whatever";
        var regexp = new RegExp(regexstring, "gi");
        var str = "whateverTest";
        var str2 = str.replace(regexp, "other");
        document.write(str2);


        Then you can construct regexstring in any way you want.



        You can read more about it here.






        share|improve this answer

















        • 5




          +1 for the full sample, RegExp params, and link.
          – Jason McCreary
          Oct 27 '10 at 0:45












        • This does not work for me on chrome. :(
          – Ankit Tanna
          May 8 '15 at 9:15










        • var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
          – Ankit Tanna
          May 8 '15 at 9:19

















        up vote
        67
        down vote













        You can use the RegExp object:



        var regexstring = "whatever";
        var regexp = new RegExp(regexstring, "gi");
        var str = "whateverTest";
        var str2 = str.replace(regexp, "other");
        document.write(str2);


        Then you can construct regexstring in any way you want.



        You can read more about it here.






        share|improve this answer

















        • 5




          +1 for the full sample, RegExp params, and link.
          – Jason McCreary
          Oct 27 '10 at 0:45












        • This does not work for me on chrome. :(
          – Ankit Tanna
          May 8 '15 at 9:15










        • var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
          – Ankit Tanna
          May 8 '15 at 9:19















        up vote
        67
        down vote










        up vote
        67
        down vote









        You can use the RegExp object:



        var regexstring = "whatever";
        var regexp = new RegExp(regexstring, "gi");
        var str = "whateverTest";
        var str2 = str.replace(regexp, "other");
        document.write(str2);


        Then you can construct regexstring in any way you want.



        You can read more about it here.






        share|improve this answer












        You can use the RegExp object:



        var regexstring = "whatever";
        var regexp = new RegExp(regexstring, "gi");
        var str = "whateverTest";
        var str2 = str.replace(regexp, "other");
        document.write(str2);


        Then you can construct regexstring in any way you want.



        You can read more about it here.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 27 '10 at 0:40









        steinar

        7,77511730




        7,77511730








        • 5




          +1 for the full sample, RegExp params, and link.
          – Jason McCreary
          Oct 27 '10 at 0:45












        • This does not work for me on chrome. :(
          – Ankit Tanna
          May 8 '15 at 9:15










        • var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
          – Ankit Tanna
          May 8 '15 at 9:19
















        • 5




          +1 for the full sample, RegExp params, and link.
          – Jason McCreary
          Oct 27 '10 at 0:45












        • This does not work for me on chrome. :(
          – Ankit Tanna
          May 8 '15 at 9:15










        • var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
          – Ankit Tanna
          May 8 '15 at 9:19










        5




        5




        +1 for the full sample, RegExp params, and link.
        – Jason McCreary
        Oct 27 '10 at 0:45






        +1 for the full sample, RegExp params, and link.
        – Jason McCreary
        Oct 27 '10 at 0:45














        This does not work for me on chrome. :(
        – Ankit Tanna
        May 8 '15 at 9:15




        This does not work for me on chrome. :(
        – Ankit Tanna
        May 8 '15 at 9:15












        var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
        – Ankit Tanna
        May 8 '15 at 9:19






        var characterCount = parseInt(attrs.limitCharacterCount); console.log(characterCount); var specialCharactersValidation = new RegExp("/^[a-zA-Z0-9]{"+characterCount+"}$/"); //^[a-zA-Z0-9]{7}$// requestShipmentDirectives.js:76 false main.js:46 Uncaught TypeError: Cannot read property 'offsetWidth' of null This is what is happening when I make the RegEx Dynamic.
        – Ankit Tanna
        May 8 '15 at 9:19












        up vote
        28
        down vote













        To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.



        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }


        of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:



        function regexEscape(str) {
        return str.replace(/[-/\^$*+?.()|[]{}]/g, '\$&')
        }

        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        input = regexEscape(input);
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }





        share|improve this answer























        • The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
          – Michael Rader
          Dec 30 '16 at 1:47








        • 1




          @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
          – zzzzBov
          Dec 30 '16 at 3:49










        • lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
          – Michael Rader
          Dec 30 '16 at 4:43















        up vote
        28
        down vote













        To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.



        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }


        of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:



        function regexEscape(str) {
        return str.replace(/[-/\^$*+?.()|[]{}]/g, '\$&')
        }

        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        input = regexEscape(input);
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }





        share|improve this answer























        • The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
          – Michael Rader
          Dec 30 '16 at 1:47








        • 1




          @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
          – zzzzBov
          Dec 30 '16 at 3:49










        • lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
          – Michael Rader
          Dec 30 '16 at 4:43













        up vote
        28
        down vote










        up vote
        28
        down vote









        To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.



        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }


        of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:



        function regexEscape(str) {
        return str.replace(/[-/\^$*+?.()|[]{}]/g, '\$&')
        }

        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        input = regexEscape(input);
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }





        share|improve this answer














        To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.



        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }


        of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:



        function regexEscape(str) {
        return str.replace(/[-/\^$*+?.()|[]{}]/g, '\$&')
        }

        function reg(input) {
        var flags;
        //could be any combination of 'g', 'i', and 'm'
        flags = 'g';
        input = regexEscape(input);
        return new RegExp('ReGeX' + input + 'ReGeX', flags);
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 23 '17 at 11:55









        Community

        11




        11










        answered Jan 16 '13 at 13:29









        zzzzBov

        129k33261305




        129k33261305












        • The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
          – Michael Rader
          Dec 30 '16 at 1:47








        • 1




          @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
          – zzzzBov
          Dec 30 '16 at 3:49










        • lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
          – Michael Rader
          Dec 30 '16 at 4:43


















        • The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
          – Michael Rader
          Dec 30 '16 at 1:47








        • 1




          @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
          – zzzzBov
          Dec 30 '16 at 3:49










        • lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
          – Michael Rader
          Dec 30 '16 at 4:43
















        The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
        – Michael Rader
        Dec 30 '16 at 1:47






        The only way this worked for me was if I deleted ReGeX text. So I used: return new RegExp(input, flags);
        – Michael Rader
        Dec 30 '16 at 1:47






        1




        1




        @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
        – zzzzBov
        Dec 30 '16 at 3:49




        @MichaelRader, yes, the "ReGeX" text was part of the question and used as an example, not as something that's required to make the code work.
        – zzzzBov
        Dec 30 '16 at 3:49












        lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
        – Michael Rader
        Dec 30 '16 at 4:43




        lol just realized that was just your placeholder, but as a noob this took me awhile to figure out. Thanks.
        – Michael Rader
        Dec 30 '16 at 4:43










        up vote
        6
        down vote













        You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.



        You can also use RegExp constructor to pass flags in (see the docs).






        share|improve this answer

























          up vote
          6
          down vote













          You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.



          You can also use RegExp constructor to pass flags in (see the docs).






          share|improve this answer























            up vote
            6
            down vote










            up vote
            6
            down vote









            You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.



            You can also use RegExp constructor to pass flags in (see the docs).






            share|improve this answer












            You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.



            You can also use RegExp constructor to pass flags in (see the docs).







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 27 '10 at 0:33









            Nikita Rybak

            56.2k18137163




            56.2k18137163






















                up vote
                3
                down vote













                if you're using es6 template literals are an option...



                string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")





                share|improve this answer



























                  up vote
                  3
                  down vote













                  if you're using es6 template literals are an option...



                  string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")





                  share|improve this answer

























                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote









                    if you're using es6 template literals are an option...



                    string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")





                    share|improve this answer














                    if you're using es6 template literals are an option...



                    string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 5 at 10:28

























                    answered Apr 5 at 10:19









                    shunryu111

                    2,72531513




                    2,72531513






















                        up vote
                        2
                        down vote













                        accepted answer doesn't work for me and doesn't follow MDN examples



                        see the 'Description' section in above link



                        I'd go with the following it's working for me:



                        let stringThatIsGoingToChange = 'findMe';
                        let flagsYouWant = 'gi' //simple string with flags
                        let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

                        // that makes dynamicRegExp = /findMe/gi





                        share|improve this answer























                        • It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
                          – HelloWorldPeace
                          Jun 23 at 19:38












                        • flagsYouWant is a string, not a variable, so that won't work
                          – macasas
                          Sep 14 at 11:24










                        • @macasas right you are i think i fixed thanks!
                          – Timothy Mitchell
                          Oct 4 at 15:40















                        up vote
                        2
                        down vote













                        accepted answer doesn't work for me and doesn't follow MDN examples



                        see the 'Description' section in above link



                        I'd go with the following it's working for me:



                        let stringThatIsGoingToChange = 'findMe';
                        let flagsYouWant = 'gi' //simple string with flags
                        let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

                        // that makes dynamicRegExp = /findMe/gi





                        share|improve this answer























                        • It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
                          – HelloWorldPeace
                          Jun 23 at 19:38












                        • flagsYouWant is a string, not a variable, so that won't work
                          – macasas
                          Sep 14 at 11:24










                        • @macasas right you are i think i fixed thanks!
                          – Timothy Mitchell
                          Oct 4 at 15:40













                        up vote
                        2
                        down vote










                        up vote
                        2
                        down vote









                        accepted answer doesn't work for me and doesn't follow MDN examples



                        see the 'Description' section in above link



                        I'd go with the following it's working for me:



                        let stringThatIsGoingToChange = 'findMe';
                        let flagsYouWant = 'gi' //simple string with flags
                        let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

                        // that makes dynamicRegExp = /findMe/gi





                        share|improve this answer














                        accepted answer doesn't work for me and doesn't follow MDN examples



                        see the 'Description' section in above link



                        I'd go with the following it's working for me:



                        let stringThatIsGoingToChange = 'findMe';
                        let flagsYouWant = 'gi' //simple string with flags
                        let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

                        // that makes dynamicRegExp = /findMe/gi






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Oct 4 at 15:39

























                        answered Jun 7 at 22:52









                        Timothy Mitchell

                        213




                        213












                        • It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
                          – HelloWorldPeace
                          Jun 23 at 19:38












                        • flagsYouWant is a string, not a variable, so that won't work
                          – macasas
                          Sep 14 at 11:24










                        • @macasas right you are i think i fixed thanks!
                          – Timothy Mitchell
                          Oct 4 at 15:40


















                        • It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
                          – HelloWorldPeace
                          Jun 23 at 19:38












                        • flagsYouWant is a string, not a variable, so that won't work
                          – macasas
                          Sep 14 at 11:24










                        • @macasas right you are i think i fixed thanks!
                          – Timothy Mitchell
                          Oct 4 at 15:40
















                        It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
                        – HelloWorldPeace
                        Jun 23 at 19:38






                        It still works. The issue is that 'ReGeX' + testVar +' ReGeX' makes the solution confusing. Adding an actually example would clear things up in my opinion. var testVar = '321'; var regex = new RegExp( "[" + testVar + "]{2}", "g" ); // above equivalent to /[321]{2}/g
                        – HelloWorldPeace
                        Jun 23 at 19:38














                        flagsYouWant is a string, not a variable, so that won't work
                        – macasas
                        Sep 14 at 11:24




                        flagsYouWant is a string, not a variable, so that won't work
                        – macasas
                        Sep 14 at 11:24












                        @macasas right you are i think i fixed thanks!
                        – Timothy Mitchell
                        Oct 4 at 15:40




                        @macasas right you are i think i fixed thanks!
                        – Timothy Mitchell
                        Oct 4 at 15:40










                        up vote
                        1
                        down vote













                        Here's an pretty useless function that return values wrapped by specific characters. :)



                        jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/



                        function getValsWrappedIn(str,c1,c2){
                        var rg = new RegExp("(?<=\"+c1+")(.*?)(?=\"+c2+")","g");
                        return str.match(rg);
                        }

                        var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
                        var results = getValsWrappedIn(exampleStr,"(",")")

                        // Will return array ["5","19","thingy"]
                        console.log(results)





                        share|improve this answer



























                          up vote
                          1
                          down vote













                          Here's an pretty useless function that return values wrapped by specific characters. :)



                          jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/



                          function getValsWrappedIn(str,c1,c2){
                          var rg = new RegExp("(?<=\"+c1+")(.*?)(?=\"+c2+")","g");
                          return str.match(rg);
                          }

                          var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
                          var results = getValsWrappedIn(exampleStr,"(",")")

                          // Will return array ["5","19","thingy"]
                          console.log(results)





                          share|improve this answer

























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            Here's an pretty useless function that return values wrapped by specific characters. :)



                            jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/



                            function getValsWrappedIn(str,c1,c2){
                            var rg = new RegExp("(?<=\"+c1+")(.*?)(?=\"+c2+")","g");
                            return str.match(rg);
                            }

                            var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
                            var results = getValsWrappedIn(exampleStr,"(",")")

                            // Will return array ["5","19","thingy"]
                            console.log(results)





                            share|improve this answer














                            Here's an pretty useless function that return values wrapped by specific characters. :)



                            jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/



                            function getValsWrappedIn(str,c1,c2){
                            var rg = new RegExp("(?<=\"+c1+")(.*?)(?=\"+c2+")","g");
                            return str.match(rg);
                            }

                            var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
                            var results = getValsWrappedIn(exampleStr,"(",")")

                            // Will return array ["5","19","thingy"]
                            console.log(results)






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Aug 7 at 22:14

























                            answered Feb 17 at 1:20









                            Jakob Sternberg

                            1,2171010




                            1,2171010






























                                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.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • 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%2f4029109%2fjavascript-regex-how-to-put-a-variable-inside-a-regular-expression%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

                                What visual should I use to simply compare current year value vs last year in Power BI desktop

                                Alexandru Averescu

                                Trompette piccolo