Can you create JavaScript regexes on the fly using string variables?











up vote
117
down vote

favorite
13












Say I wanted to make the following re-usable:



function replace_foo(target, replacement) {
return target.replace("string_to_replace",replacement);
}


I might do something like this:



function replace_foo(target, string_to_replace, replacement) {
return target.replace(string_to_replace,replacement);
}


With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:



function replace_foo(target, string_to_replace, replacement) {
return target.replace(/^string_to_replace/,replacement);
}


This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:



function replace_foo(target, string_to_replace, replacement) {
var regex = "/^" + string_to_replace + "/";
return target.replace(regex,replacement);
}









share|improve this question


























    up vote
    117
    down vote

    favorite
    13












    Say I wanted to make the following re-usable:



    function replace_foo(target, replacement) {
    return target.replace("string_to_replace",replacement);
    }


    I might do something like this:



    function replace_foo(target, string_to_replace, replacement) {
    return target.replace(string_to_replace,replacement);
    }


    With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:



    function replace_foo(target, string_to_replace, replacement) {
    return target.replace(/^string_to_replace/,replacement);
    }


    This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:



    function replace_foo(target, string_to_replace, replacement) {
    var regex = "/^" + string_to_replace + "/";
    return target.replace(regex,replacement);
    }









    share|improve this question
























      up vote
      117
      down vote

      favorite
      13









      up vote
      117
      down vote

      favorite
      13






      13





      Say I wanted to make the following re-usable:



      function replace_foo(target, replacement) {
      return target.replace("string_to_replace",replacement);
      }


      I might do something like this:



      function replace_foo(target, string_to_replace, replacement) {
      return target.replace(string_to_replace,replacement);
      }


      With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:



      function replace_foo(target, string_to_replace, replacement) {
      return target.replace(/^string_to_replace/,replacement);
      }


      This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:



      function replace_foo(target, string_to_replace, replacement) {
      var regex = "/^" + string_to_replace + "/";
      return target.replace(regex,replacement);
      }









      share|improve this question













      Say I wanted to make the following re-usable:



      function replace_foo(target, replacement) {
      return target.replace("string_to_replace",replacement);
      }


      I might do something like this:



      function replace_foo(target, string_to_replace, replacement) {
      return target.replace(string_to_replace,replacement);
      }


      With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:



      function replace_foo(target, string_to_replace, replacement) {
      return target.replace(/^string_to_replace/,replacement);
      }


      This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:



      function replace_foo(target, string_to_replace, replacement) {
      var regex = "/^" + string_to_replace + "/";
      return target.replace(regex,replacement);
      }






      javascript regex






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 6 '10 at 22:26









      buley

      14.3k136794




      14.3k136794
























          6 Answers
          6






          active

          oldest

          votes

















          up vote
          182
          down vote



          accepted










          There's new RegExp(string, flags) where flags are g or i. So



          'GODzilla'.replace( new RegExp('god', 'i'), '' )


          evaluates to



          zilla





          share|improve this answer

















          • 26




            And omit the / regex delimiters when using this form too.
            – cdhowie
            Dec 6 '10 at 22:28










          • Thanks meder. And cdhowie: great comment. I would have tried the other way first.
            – buley
            Dec 6 '10 at 22:39


















          up vote
          103
          down vote














          With string literals this is easy enough.




          Not really! The example only replaces the first occurrence of string_to_replace. More commonly you want to replace all occurrences, in which case, you have to convert the string into a global (/.../g) RegExp. You can do this from a string using the new RegExp constructor:



          new RegExp(string_to_replace, 'g')


          The problem with this is that any regex-special characters in the string literal will behave in their special ways instead of being normal characters. You would have to backslash-escape them to fix that. Unfortunately, there's not a built-in function to do this for you, so here's one you can use:



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


          Note also that when you use a RegExp in replace(), the replacement string now has a special character too, $. This must also be escaped if you want to have a literal $ in your replacement text!



          function escapeSubstitute(s) {
          return s.replace(/$/g, '$$$$');
          }


          (Four $s because that is itself a replacement string—argh!)



          Now you can implement global string replacement with RegExp:



          function replace_foo(target, string_to_replace, replacement) {
          var relit= escapeRegExp(string_to_replace);
          var sub= escapeSubstitute(replacement);
          var re= new RegExp(relit, 'g');
          return target.replace(re, sub);
          }


          What a pain. Luckily if all you want to do is a straight string replace with no additional parts of regex, there is a quicker way:



          s.split(string_to_replace).join(replacement)


          ...and that's all. This is a commonly-understood idiom.




          say I want to replace everything but string_to_replace




          What does that mean, you want to replace all stretches of text not taking part in a match against the string? A replacement with ^ certainly doesn't this, because ^ means a start-of-string token, not a negation. ^ is only a negation in character groups. There are also negative lookaheads (?!...), but there are problems with that in JScript so you should generally avoid it.



          You might try matching ‘everything up to’ the string, and using a function to discard any empty stretch between matching strings:



          var re= new RegExp('(.*)($|'+escapeRegExp(string_to_find)+')')
          return target.replace(re, function(match) {
          return match[1]===''? match[2] : replacement+match[2];
          });


          Here, again, a split might be simpler:



          var parts= target.split(string_to_match);
          for (var i= parts.length; i-->0;)
          if (parts[i]!=='')
          parts[i]= replacement;
          return parts.join(string_to_match);





          share|improve this answer



















          • 9




            +1, very thorough, and under-appreciated.
            – Tim Down
            Dec 7 '10 at 0:24


















          up vote
          10
          down vote













          As the others have said, use new RegExp(pattern, flags) to do this. It is worth noting that you will be passing string literals into this constructor, so every backslash will have to be escaped. If, for instance you wanted your regex to match a backslash, you would need to say new RegExp('\\'), whereas the regex literal would only need to be /\/. Depending on how you intend to use this, you should be wary of passing user input to such a function without adequate preprocessing (escaping special characters, etc.) Without this, your users may get some very unexpected results.






          share|improve this answer

















          • 3




            This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
            – Byson
            Jan 6 '15 at 14:17










          • I KNOW about this problem and still get stuck on it. So this was helpful.
            – J.M.I. MADISON
            Aug 18 at 4:21


















          up vote
          5
          down vote













          Yes you can.



          https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions



          function replace_foo(target, string_to_replace, replacement) {
          var regex = new RegExp("^" + string_to_replace);
          return target.replace(regex, replacement);
          }





          share|improve this answer




























            up vote
            0
            down vote













            I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)



            function getHighlightedText(basicString, filterString) {

            if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

            return basicString.replace(new RegExp(filterString.replace(/[-/\^$*+?.()|[]{}]/g, '\\$&'), 'gi'),
            function(match)
            {return "<mark>"+match+"</mark>"});

            }


            http://jsfiddle.net/cdbzL/1258/






            share|improve this answer




























              up vote
              0
              down vote













              A really simple solution to this is this:



              function replace(target, string_to_replace, replacement) {
              return target.split(string_to_replace).join(replacement);
              }


              No need for Regexes at all



              It also seems to be the fastest on modern browsers https://jsperf.com/replace-vs-split-join-vs-replaceall






              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%2f4371565%2fcan-you-create-javascript-regexes-on-the-fly-using-string-variables%23new-answer', 'question_page');
                }
                );

                Post as a guest
































                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                182
                down vote



                accepted










                There's new RegExp(string, flags) where flags are g or i. So



                'GODzilla'.replace( new RegExp('god', 'i'), '' )


                evaluates to



                zilla





                share|improve this answer

















                • 26




                  And omit the / regex delimiters when using this form too.
                  – cdhowie
                  Dec 6 '10 at 22:28










                • Thanks meder. And cdhowie: great comment. I would have tried the other way first.
                  – buley
                  Dec 6 '10 at 22:39















                up vote
                182
                down vote



                accepted










                There's new RegExp(string, flags) where flags are g or i. So



                'GODzilla'.replace( new RegExp('god', 'i'), '' )


                evaluates to



                zilla





                share|improve this answer

















                • 26




                  And omit the / regex delimiters when using this form too.
                  – cdhowie
                  Dec 6 '10 at 22:28










                • Thanks meder. And cdhowie: great comment. I would have tried the other way first.
                  – buley
                  Dec 6 '10 at 22:39













                up vote
                182
                down vote



                accepted







                up vote
                182
                down vote



                accepted






                There's new RegExp(string, flags) where flags are g or i. So



                'GODzilla'.replace( new RegExp('god', 'i'), '' )


                evaluates to



                zilla





                share|improve this answer












                There's new RegExp(string, flags) where flags are g or i. So



                'GODzilla'.replace( new RegExp('god', 'i'), '' )


                evaluates to



                zilla






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 6 '10 at 22:27









                meder omuraliev

                136k54337407




                136k54337407








                • 26




                  And omit the / regex delimiters when using this form too.
                  – cdhowie
                  Dec 6 '10 at 22:28










                • Thanks meder. And cdhowie: great comment. I would have tried the other way first.
                  – buley
                  Dec 6 '10 at 22:39














                • 26




                  And omit the / regex delimiters when using this form too.
                  – cdhowie
                  Dec 6 '10 at 22:28










                • Thanks meder. And cdhowie: great comment. I would have tried the other way first.
                  – buley
                  Dec 6 '10 at 22:39








                26




                26




                And omit the / regex delimiters when using this form too.
                – cdhowie
                Dec 6 '10 at 22:28




                And omit the / regex delimiters when using this form too.
                – cdhowie
                Dec 6 '10 at 22:28












                Thanks meder. And cdhowie: great comment. I would have tried the other way first.
                – buley
                Dec 6 '10 at 22:39




                Thanks meder. And cdhowie: great comment. I would have tried the other way first.
                – buley
                Dec 6 '10 at 22:39












                up vote
                103
                down vote














                With string literals this is easy enough.




                Not really! The example only replaces the first occurrence of string_to_replace. More commonly you want to replace all occurrences, in which case, you have to convert the string into a global (/.../g) RegExp. You can do this from a string using the new RegExp constructor:



                new RegExp(string_to_replace, 'g')


                The problem with this is that any regex-special characters in the string literal will behave in their special ways instead of being normal characters. You would have to backslash-escape them to fix that. Unfortunately, there's not a built-in function to do this for you, so here's one you can use:



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


                Note also that when you use a RegExp in replace(), the replacement string now has a special character too, $. This must also be escaped if you want to have a literal $ in your replacement text!



                function escapeSubstitute(s) {
                return s.replace(/$/g, '$$$$');
                }


                (Four $s because that is itself a replacement string—argh!)



                Now you can implement global string replacement with RegExp:



                function replace_foo(target, string_to_replace, replacement) {
                var relit= escapeRegExp(string_to_replace);
                var sub= escapeSubstitute(replacement);
                var re= new RegExp(relit, 'g');
                return target.replace(re, sub);
                }


                What a pain. Luckily if all you want to do is a straight string replace with no additional parts of regex, there is a quicker way:



                s.split(string_to_replace).join(replacement)


                ...and that's all. This is a commonly-understood idiom.




                say I want to replace everything but string_to_replace




                What does that mean, you want to replace all stretches of text not taking part in a match against the string? A replacement with ^ certainly doesn't this, because ^ means a start-of-string token, not a negation. ^ is only a negation in character groups. There are also negative lookaheads (?!...), but there are problems with that in JScript so you should generally avoid it.



                You might try matching ‘everything up to’ the string, and using a function to discard any empty stretch between matching strings:



                var re= new RegExp('(.*)($|'+escapeRegExp(string_to_find)+')')
                return target.replace(re, function(match) {
                return match[1]===''? match[2] : replacement+match[2];
                });


                Here, again, a split might be simpler:



                var parts= target.split(string_to_match);
                for (var i= parts.length; i-->0;)
                if (parts[i]!=='')
                parts[i]= replacement;
                return parts.join(string_to_match);





                share|improve this answer



















                • 9




                  +1, very thorough, and under-appreciated.
                  – Tim Down
                  Dec 7 '10 at 0:24















                up vote
                103
                down vote














                With string literals this is easy enough.




                Not really! The example only replaces the first occurrence of string_to_replace. More commonly you want to replace all occurrences, in which case, you have to convert the string into a global (/.../g) RegExp. You can do this from a string using the new RegExp constructor:



                new RegExp(string_to_replace, 'g')


                The problem with this is that any regex-special characters in the string literal will behave in their special ways instead of being normal characters. You would have to backslash-escape them to fix that. Unfortunately, there's not a built-in function to do this for you, so here's one you can use:



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


                Note also that when you use a RegExp in replace(), the replacement string now has a special character too, $. This must also be escaped if you want to have a literal $ in your replacement text!



                function escapeSubstitute(s) {
                return s.replace(/$/g, '$$$$');
                }


                (Four $s because that is itself a replacement string—argh!)



                Now you can implement global string replacement with RegExp:



                function replace_foo(target, string_to_replace, replacement) {
                var relit= escapeRegExp(string_to_replace);
                var sub= escapeSubstitute(replacement);
                var re= new RegExp(relit, 'g');
                return target.replace(re, sub);
                }


                What a pain. Luckily if all you want to do is a straight string replace with no additional parts of regex, there is a quicker way:



                s.split(string_to_replace).join(replacement)


                ...and that's all. This is a commonly-understood idiom.




                say I want to replace everything but string_to_replace




                What does that mean, you want to replace all stretches of text not taking part in a match against the string? A replacement with ^ certainly doesn't this, because ^ means a start-of-string token, not a negation. ^ is only a negation in character groups. There are also negative lookaheads (?!...), but there are problems with that in JScript so you should generally avoid it.



                You might try matching ‘everything up to’ the string, and using a function to discard any empty stretch between matching strings:



                var re= new RegExp('(.*)($|'+escapeRegExp(string_to_find)+')')
                return target.replace(re, function(match) {
                return match[1]===''? match[2] : replacement+match[2];
                });


                Here, again, a split might be simpler:



                var parts= target.split(string_to_match);
                for (var i= parts.length; i-->0;)
                if (parts[i]!=='')
                parts[i]= replacement;
                return parts.join(string_to_match);





                share|improve this answer



















                • 9




                  +1, very thorough, and under-appreciated.
                  – Tim Down
                  Dec 7 '10 at 0:24













                up vote
                103
                down vote










                up vote
                103
                down vote










                With string literals this is easy enough.




                Not really! The example only replaces the first occurrence of string_to_replace. More commonly you want to replace all occurrences, in which case, you have to convert the string into a global (/.../g) RegExp. You can do this from a string using the new RegExp constructor:



                new RegExp(string_to_replace, 'g')


                The problem with this is that any regex-special characters in the string literal will behave in their special ways instead of being normal characters. You would have to backslash-escape them to fix that. Unfortunately, there's not a built-in function to do this for you, so here's one you can use:



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


                Note also that when you use a RegExp in replace(), the replacement string now has a special character too, $. This must also be escaped if you want to have a literal $ in your replacement text!



                function escapeSubstitute(s) {
                return s.replace(/$/g, '$$$$');
                }


                (Four $s because that is itself a replacement string—argh!)



                Now you can implement global string replacement with RegExp:



                function replace_foo(target, string_to_replace, replacement) {
                var relit= escapeRegExp(string_to_replace);
                var sub= escapeSubstitute(replacement);
                var re= new RegExp(relit, 'g');
                return target.replace(re, sub);
                }


                What a pain. Luckily if all you want to do is a straight string replace with no additional parts of regex, there is a quicker way:



                s.split(string_to_replace).join(replacement)


                ...and that's all. This is a commonly-understood idiom.




                say I want to replace everything but string_to_replace




                What does that mean, you want to replace all stretches of text not taking part in a match against the string? A replacement with ^ certainly doesn't this, because ^ means a start-of-string token, not a negation. ^ is only a negation in character groups. There are also negative lookaheads (?!...), but there are problems with that in JScript so you should generally avoid it.



                You might try matching ‘everything up to’ the string, and using a function to discard any empty stretch between matching strings:



                var re= new RegExp('(.*)($|'+escapeRegExp(string_to_find)+')')
                return target.replace(re, function(match) {
                return match[1]===''? match[2] : replacement+match[2];
                });


                Here, again, a split might be simpler:



                var parts= target.split(string_to_match);
                for (var i= parts.length; i-->0;)
                if (parts[i]!=='')
                parts[i]= replacement;
                return parts.join(string_to_match);





                share|improve this answer















                With string literals this is easy enough.




                Not really! The example only replaces the first occurrence of string_to_replace. More commonly you want to replace all occurrences, in which case, you have to convert the string into a global (/.../g) RegExp. You can do this from a string using the new RegExp constructor:



                new RegExp(string_to_replace, 'g')


                The problem with this is that any regex-special characters in the string literal will behave in their special ways instead of being normal characters. You would have to backslash-escape them to fix that. Unfortunately, there's not a built-in function to do this for you, so here's one you can use:



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


                Note also that when you use a RegExp in replace(), the replacement string now has a special character too, $. This must also be escaped if you want to have a literal $ in your replacement text!



                function escapeSubstitute(s) {
                return s.replace(/$/g, '$$$$');
                }


                (Four $s because that is itself a replacement string—argh!)



                Now you can implement global string replacement with RegExp:



                function replace_foo(target, string_to_replace, replacement) {
                var relit= escapeRegExp(string_to_replace);
                var sub= escapeSubstitute(replacement);
                var re= new RegExp(relit, 'g');
                return target.replace(re, sub);
                }


                What a pain. Luckily if all you want to do is a straight string replace with no additional parts of regex, there is a quicker way:



                s.split(string_to_replace).join(replacement)


                ...and that's all. This is a commonly-understood idiom.




                say I want to replace everything but string_to_replace




                What does that mean, you want to replace all stretches of text not taking part in a match against the string? A replacement with ^ certainly doesn't this, because ^ means a start-of-string token, not a negation. ^ is only a negation in character groups. There are also negative lookaheads (?!...), but there are problems with that in JScript so you should generally avoid it.



                You might try matching ‘everything up to’ the string, and using a function to discard any empty stretch between matching strings:



                var re= new RegExp('(.*)($|'+escapeRegExp(string_to_find)+')')
                return target.replace(re, function(match) {
                return match[1]===''? match[2] : replacement+match[2];
                });


                Here, again, a split might be simpler:



                var parts= target.split(string_to_match);
                for (var i= parts.length; i-->0;)
                if (parts[i]!=='')
                parts[i]= replacement;
                return parts.join(string_to_match);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 14 '15 at 21:34









                Hans

                539517




                539517










                answered Dec 6 '10 at 23:03









                bobince

                436k88560762




                436k88560762








                • 9




                  +1, very thorough, and under-appreciated.
                  – Tim Down
                  Dec 7 '10 at 0:24














                • 9




                  +1, very thorough, and under-appreciated.
                  – Tim Down
                  Dec 7 '10 at 0:24








                9




                9




                +1, very thorough, and under-appreciated.
                – Tim Down
                Dec 7 '10 at 0:24




                +1, very thorough, and under-appreciated.
                – Tim Down
                Dec 7 '10 at 0:24










                up vote
                10
                down vote













                As the others have said, use new RegExp(pattern, flags) to do this. It is worth noting that you will be passing string literals into this constructor, so every backslash will have to be escaped. If, for instance you wanted your regex to match a backslash, you would need to say new RegExp('\\'), whereas the regex literal would only need to be /\/. Depending on how you intend to use this, you should be wary of passing user input to such a function without adequate preprocessing (escaping special characters, etc.) Without this, your users may get some very unexpected results.






                share|improve this answer

















                • 3




                  This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
                  – Byson
                  Jan 6 '15 at 14:17










                • I KNOW about this problem and still get stuck on it. So this was helpful.
                  – J.M.I. MADISON
                  Aug 18 at 4:21















                up vote
                10
                down vote













                As the others have said, use new RegExp(pattern, flags) to do this. It is worth noting that you will be passing string literals into this constructor, so every backslash will have to be escaped. If, for instance you wanted your regex to match a backslash, you would need to say new RegExp('\\'), whereas the regex literal would only need to be /\/. Depending on how you intend to use this, you should be wary of passing user input to such a function without adequate preprocessing (escaping special characters, etc.) Without this, your users may get some very unexpected results.






                share|improve this answer

















                • 3




                  This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
                  – Byson
                  Jan 6 '15 at 14:17










                • I KNOW about this problem and still get stuck on it. So this was helpful.
                  – J.M.I. MADISON
                  Aug 18 at 4:21













                up vote
                10
                down vote










                up vote
                10
                down vote









                As the others have said, use new RegExp(pattern, flags) to do this. It is worth noting that you will be passing string literals into this constructor, so every backslash will have to be escaped. If, for instance you wanted your regex to match a backslash, you would need to say new RegExp('\\'), whereas the regex literal would only need to be /\/. Depending on how you intend to use this, you should be wary of passing user input to such a function without adequate preprocessing (escaping special characters, etc.) Without this, your users may get some very unexpected results.






                share|improve this answer












                As the others have said, use new RegExp(pattern, flags) to do this. It is worth noting that you will be passing string literals into this constructor, so every backslash will have to be escaped. If, for instance you wanted your regex to match a backslash, you would need to say new RegExp('\\'), whereas the regex literal would only need to be /\/. Depending on how you intend to use this, you should be wary of passing user input to such a function without adequate preprocessing (escaping special characters, etc.) Without this, your users may get some very unexpected results.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 6 '10 at 22:51









                Kent

                41125




                41125








                • 3




                  This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
                  – Byson
                  Jan 6 '15 at 14:17










                • I KNOW about this problem and still get stuck on it. So this was helpful.
                  – J.M.I. MADISON
                  Aug 18 at 4:21














                • 3




                  This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
                  – Byson
                  Jan 6 '15 at 14:17










                • I KNOW about this problem and still get stuck on it. So this was helpful.
                  – J.M.I. MADISON
                  Aug 18 at 4:21








                3




                3




                This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
                – Byson
                Jan 6 '15 at 14:17




                This answer, while not the most detailed, does mention a crucial detail which I was just stuck on for an hour: escape any special sequences. For example, I was searching for a word starting with a certain term, so the regex I'd need is /b[term]B/, but when constructing it I need to call new RegExp("\b"+ term + "\B"). Small but important difference, and hard to spot since using it as a regex directly does work as expected.
                – Byson
                Jan 6 '15 at 14:17












                I KNOW about this problem and still get stuck on it. So this was helpful.
                – J.M.I. MADISON
                Aug 18 at 4:21




                I KNOW about this problem and still get stuck on it. So this was helpful.
                – J.M.I. MADISON
                Aug 18 at 4:21










                up vote
                5
                down vote













                Yes you can.



                https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions



                function replace_foo(target, string_to_replace, replacement) {
                var regex = new RegExp("^" + string_to_replace);
                return target.replace(regex, replacement);
                }





                share|improve this answer

























                  up vote
                  5
                  down vote













                  Yes you can.



                  https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions



                  function replace_foo(target, string_to_replace, replacement) {
                  var regex = new RegExp("^" + string_to_replace);
                  return target.replace(regex, replacement);
                  }





                  share|improve this answer























                    up vote
                    5
                    down vote










                    up vote
                    5
                    down vote









                    Yes you can.



                    https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions



                    function replace_foo(target, string_to_replace, replacement) {
                    var regex = new RegExp("^" + string_to_replace);
                    return target.replace(regex, replacement);
                    }





                    share|improve this answer












                    Yes you can.



                    https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions



                    function replace_foo(target, string_to_replace, replacement) {
                    var regex = new RegExp("^" + string_to_replace);
                    return target.replace(regex, replacement);
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 6 '10 at 22:41









                    Kristof Neirynck

                    2,4612039




                    2,4612039






















                        up vote
                        0
                        down vote













                        I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)



                        function getHighlightedText(basicString, filterString) {

                        if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

                        return basicString.replace(new RegExp(filterString.replace(/[-/\^$*+?.()|[]{}]/g, '\\$&'), 'gi'),
                        function(match)
                        {return "<mark>"+match+"</mark>"});

                        }


                        http://jsfiddle.net/cdbzL/1258/






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)



                          function getHighlightedText(basicString, filterString) {

                          if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

                          return basicString.replace(new RegExp(filterString.replace(/[-/\^$*+?.()|[]{}]/g, '\\$&'), 'gi'),
                          function(match)
                          {return "<mark>"+match+"</mark>"});

                          }


                          http://jsfiddle.net/cdbzL/1258/






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)



                            function getHighlightedText(basicString, filterString) {

                            if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

                            return basicString.replace(new RegExp(filterString.replace(/[-/\^$*+?.()|[]{}]/g, '\\$&'), 'gi'),
                            function(match)
                            {return "<mark>"+match+"</mark>"});

                            }


                            http://jsfiddle.net/cdbzL/1258/






                            share|improve this answer












                            I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)



                            function getHighlightedText(basicString, filterString) {

                            if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

                            return basicString.replace(new RegExp(filterString.replace(/[-/\^$*+?.()|[]{}]/g, '\\$&'), 'gi'),
                            function(match)
                            {return "<mark>"+match+"</mark>"});

                            }


                            http://jsfiddle.net/cdbzL/1258/







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 8 '17 at 15:06









                            Константин Журов

                            14718




                            14718






















                                up vote
                                0
                                down vote













                                A really simple solution to this is this:



                                function replace(target, string_to_replace, replacement) {
                                return target.split(string_to_replace).join(replacement);
                                }


                                No need for Regexes at all



                                It also seems to be the fastest on modern browsers https://jsperf.com/replace-vs-split-join-vs-replaceall






                                share|improve this answer



























                                  up vote
                                  0
                                  down vote













                                  A really simple solution to this is this:



                                  function replace(target, string_to_replace, replacement) {
                                  return target.split(string_to_replace).join(replacement);
                                  }


                                  No need for Regexes at all



                                  It also seems to be the fastest on modern browsers https://jsperf.com/replace-vs-split-join-vs-replaceall






                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    A really simple solution to this is this:



                                    function replace(target, string_to_replace, replacement) {
                                    return target.split(string_to_replace).join(replacement);
                                    }


                                    No need for Regexes at all



                                    It also seems to be the fastest on modern browsers https://jsperf.com/replace-vs-split-join-vs-replaceall






                                    share|improve this answer














                                    A really simple solution to this is this:



                                    function replace(target, string_to_replace, replacement) {
                                    return target.split(string_to_replace).join(replacement);
                                    }


                                    No need for Regexes at all



                                    It also seems to be the fastest on modern browsers https://jsperf.com/replace-vs-split-join-vs-replaceall







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Feb 9 at 23:05

























                                    answered Feb 9 at 22:56









                                    Jack Allan

                                    8,60063045




                                    8,60063045






























                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4371565%2fcan-you-create-javascript-regexes-on-the-fly-using-string-variables%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest




















































































                                        這個網誌中的熱門文章

                                        Xamarin.form Move up view when keyboard appear

                                        Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                        Anylogic : not able to use stopDelay()