How do you access the matched groups in a JavaScript regular expression?












1100














I want to match a portion of a string using a regular expression and then access that parenthesized substring:



var myString = "something format_abc"; // I want "abc"

var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);

console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)


What am I doing wrong?





I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:



"date format_%A"


Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.





The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.










share|improve this question





























    1100














    I want to match a portion of a string using a regular expression and then access that parenthesized substring:



    var myString = "something format_abc"; // I want "abc"

    var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);

    console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
    console.log(arr[1]); // Prints: undefined (???)
    console.log(arr[0]); // Prints: format_undefined (!!!)


    What am I doing wrong?





    I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:



    "date format_%A"


    Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.





    The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.










    share|improve this question



























      1100












      1100








      1100


      234





      I want to match a portion of a string using a regular expression and then access that parenthesized substring:



      var myString = "something format_abc"; // I want "abc"

      var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);

      console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
      console.log(arr[1]); // Prints: undefined (???)
      console.log(arr[0]); // Prints: format_undefined (!!!)


      What am I doing wrong?





      I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:



      "date format_%A"


      Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.





      The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.










      share|improve this question















      I want to match a portion of a string using a regular expression and then access that parenthesized substring:



      var myString = "something format_abc"; // I want "abc"

      var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);

      console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
      console.log(arr[1]); // Prints: undefined (???)
      console.log(arr[0]); // Prints: format_undefined (!!!)


      What am I doing wrong?





      I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:



      "date format_%A"


      Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.





      The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.







      javascript regex






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '17 at 11:55









      Community

      11




      11










      asked Jan 11 '09 at 7:21









      nickf

      369k171581687




      369k171581687
























          13 Answers
          13






          active

          oldest

          votes


















          1390














          You can access capturing groups like this:






          var myString = "something format_abc";
          var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
          var match = myRegexp.exec(myString);
          console.log(match[1]); // abc





          And if there are multiple matches you can iterate over them:






          var myString = "something format_abc";
          var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
          match = myRegexp.exec(myString);
          while (match != null) {
          // matched text: match[0]
          // match start: match.index
          // capturing group n: match[n]
          console.log(match[0])
          match = myRegexp.exec(myString);
          }








          share|improve this answer



















          • 94




            +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
            – ianaz
            Aug 28 '12 at 12:06








          • 5




            @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
            – spinningarrow
            Oct 16 '12 at 7:26






          • 11




            Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
            – JohnAllen
            Dec 30 '13 at 17:39






          • 21




            No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
            – George Chen
            Jun 6 '14 at 18:33








          • 2




            Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
            – Olga
            Feb 11 '16 at 11:28



















          163














          Here’s a method you can use to get the n​th capturing group for each match:






          function getMatches(string, regex, index) {
          index || (index = 1); // default to the first capturing group
          var matches = ;
          var match;
          while (match = regex.exec(string)) {
          matches.push(match[index]);
          }
          return matches;
          }


          // Example :
          var myString = 'something format_abc something format_def something format_ghi';
          var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

          // Get an array containing the first capturing group for every match
          var matches = getMatches(myString, myRegEx, 1);

          // Log results
          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
          console.log(matches);








          share|improve this answer



















          • 7




            This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
            – Rob Evans
            May 11 '13 at 12:08






          • 11




            mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
            – Druska
            Sep 4 '13 at 18:45






          • 2




            I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
            – ravishi
            Nov 21 '13 at 20:00






          • 4




            @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
            – wallacer
            Oct 29 '14 at 18:34








          • 3




            @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
            – wallacer
            Nov 12 '14 at 23:44



















          50

















          var myString = "something format_abc";
          var arr = myString.match(/bformat_(.*?)b/);
          console.log(arr[0] + " " + arr[1]);





          The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.






          share|improve this answer



















          • 1




            It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
            – B.F.
            Apr 22 '15 at 21:09












          • @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
            – PhiLho
            Apr 23 '15 at 7:41












          • I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
            – B.F.
            Apr 23 '15 at 10:43



















          23














          In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:



          var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);


          After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):



          var yourstring = 'something format_abc something format_def something format_ghi';

          var matches = ;
          yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );


          After this, I don't think I'm ever going to use .match() for hardly anything ever again.






          share|improve this answer





























            16














            Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.

            (FF2 went as far as typeof(/pattern/) == 'function')



            It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.



            Instead, use either method previously mentioned by others: RegExp#exec or String#match.

            They offer the same results:



            var regex = /(?:^|s)format_(.*?)(?:s|$)/;
            var input = "something format_abc";

            regex(input); //=> [" format_abc", "abc"]
            regex.exec(input); //=> [" format_abc", "abc"]
            input.match(regex); //=> [" format_abc", "abc"]





            share|improve this answer





























              12














              Last but not least, I found one line of code that worked fine for me (JS ES6):






              let reg = /#([S]+)/igm; // Get hashtags.
              let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

              let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
              console.log(matches);





              This will return:



              ['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']





              share|improve this answer



















              • 1




                this is works well except when match can't find anything then map doesn't work.
                – MBehtemam
                Nov 25 '17 at 11:23



















              11














              Terminology used in this answer:





              • Match indicates the result of running your RegEx pattern against your string like so: someString.match(regexPattern).


              • Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.


              • Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.*?)/g, where (.*?) would be a matched group.) These reside within matched patterns.


              Description



              To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.



              Code examples



              Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.



              Concise versions (less code, more syntactic sugar)



              These are less performant since they basically implement a forEach-loop instead of the faster for-loop.



              // Concise ES6/ES2015 syntax
              const searchString =
              (string, pattern) =>
              string
              .match(new RegExp(pattern.source, pattern.flags))
              .map(match =>
              new RegExp(pattern.source, pattern.flags)
              .exec(match));

              // Or if you will, with ES5 syntax
              function searchString(string, pattern) {
              return string
              .match(new RegExp(pattern.source, pattern.flags))
              .map(match =>
              new RegExp(pattern.source, pattern.flags)
              .exec(match));
              }

              let string = "something format_abc",
              pattern = /(?:^|s)format_(.*?)(?:s|$)/;

              let result = searchString(string, pattern);
              // [[" format_abc", "abc"], null]
              // The trailing `null` disappears if you add the `global` flag


              Performant versions (more code, less syntactic sugar)



              // Performant ES6/ES2015 syntax
              const searchString = (string, pattern) => {
              let result = ;

              const matches = string.match(new RegExp(pattern.source, pattern.flags));

              for (let i = 0; i < matches.length; i++) {
              result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
              }

              return result;
              };

              // Same thing, but with ES5 syntax
              function searchString(string, pattern) {
              var result = ;

              var matches = string.match(new RegExp(pattern.source, pattern.flags));

              for (var i = 0; i < matches.length; i++) {
              result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
              }

              return result;
              }

              let string = "something format_abc",
              pattern = /(?:^|s)format_(.*?)(?:s|$)/;

              let result = searchString(string, pattern);
              // [[" format_abc", "abc"], null]
              // The trailing `null` disappears if you add the `global` flag


              I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.






              share|improve this answer





























                9














                There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.



                var str = "This is cool";
                var matches = str.match(/(This is)( cool)$/);
                console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...


                Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!






                share|improve this answer



















                • 1




                  This works and feels more natural.
                  – Vidar
                  May 29 at 11:54






                • 1




                  Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                  – Shadymilkman01
                  Sep 13 at 22:00



















                7














                A one liner that is practical only if you have a single pair of parenthesis:



                while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};





                share|improve this answer

















                • 3




                  Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                  – willlma
                  Apr 6 '17 at 18:44












                • @willlma Yep!..
                  – Nabil Kadimi
                  May 23 '17 at 20:00



















                5














                Using your code:



                console.log(arr[1]);  // prints: abc
                console.log(arr[0]); // prints: format_abc


                Edit: Safari 3, if it matters.






                share|improve this answer





























                  5

















                  function getMatches(string, regex, index) {
                  index || (index = 1); // default to the first capturing group
                  var matches = ;
                  var match;
                  while (match = regex.exec(string)) {
                  matches.push(match[index]);
                  }
                  return matches;
                  }


                  // Example :
                  var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                  var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                  // Get an array containing the first capturing group for every match
                  var matches = getMatches(myString, myRegEx, 1);

                  // Log results
                  document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                  console.log(matches);








                  function getMatches(string, regex, index) {
                  index || (index = 1); // default to the first capturing group
                  var matches = ;
                  var match;
                  while (match = regex.exec(string)) {
                  matches.push(match[index]);
                  }
                  return matches;
                  }


                  // Example :
                  var myString = 'something format_abc something format_def something format_ghi';
                  var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                  // Get an array containing the first capturing group for every match
                  var matches = getMatches(myString, myRegEx, 1);

                  // Log results
                  document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                  console.log(matches);








                  share|improve this answer































                    2














                    Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:



                    /bformat_(.*?)b/


                    (But, of course, I'm not sure because I don't know the context of the regex.)






                    share|improve this answer























                    • it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                      – nickf
                      Jan 11 '09 at 12:04










                    • Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                      – PEZ
                      Jan 11 '09 at 12:21



















                    1














                    /*Regex function for extracting object from "window.location.search" string.
                    */

                    var search = "?a=3&b=4&c=7"; // Example search string

                    var getSearchObj = function (searchString) {

                    var match, key, value, obj = {};
                    var pattern = /(w+)=(w+)/g;
                    var search = searchString.substr(1); // Remove '?'

                    while (match = pattern.exec(search)) {
                    obj[match[0].split('=')[0]] = match[0].split('=')[1];
                    }

                    return obj;

                    };

                    console.log(getSearchObj(search));





                    share|improve this answer





















                      Your Answer






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

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

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

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


                      }
                      });














                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f432493%2fhow-do-you-access-the-matched-groups-in-a-javascript-regular-expression%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown

























                      13 Answers
                      13






                      active

                      oldest

                      votes








                      13 Answers
                      13






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      1390














                      You can access capturing groups like this:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      var match = myRegexp.exec(myString);
                      console.log(match[1]); // abc





                      And if there are multiple matches you can iterate over them:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      match = myRegexp.exec(myString);
                      while (match != null) {
                      // matched text: match[0]
                      // match start: match.index
                      // capturing group n: match[n]
                      console.log(match[0])
                      match = myRegexp.exec(myString);
                      }








                      share|improve this answer



















                      • 94




                        +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
                        – ianaz
                        Aug 28 '12 at 12:06








                      • 5




                        @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
                        – spinningarrow
                        Oct 16 '12 at 7:26






                      • 11




                        Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
                        – JohnAllen
                        Dec 30 '13 at 17:39






                      • 21




                        No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
                        – George Chen
                        Jun 6 '14 at 18:33








                      • 2




                        Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
                        – Olga
                        Feb 11 '16 at 11:28
















                      1390














                      You can access capturing groups like this:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      var match = myRegexp.exec(myString);
                      console.log(match[1]); // abc





                      And if there are multiple matches you can iterate over them:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      match = myRegexp.exec(myString);
                      while (match != null) {
                      // matched text: match[0]
                      // match start: match.index
                      // capturing group n: match[n]
                      console.log(match[0])
                      match = myRegexp.exec(myString);
                      }








                      share|improve this answer



















                      • 94




                        +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
                        – ianaz
                        Aug 28 '12 at 12:06








                      • 5




                        @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
                        – spinningarrow
                        Oct 16 '12 at 7:26






                      • 11




                        Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
                        – JohnAllen
                        Dec 30 '13 at 17:39






                      • 21




                        No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
                        – George Chen
                        Jun 6 '14 at 18:33








                      • 2




                        Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
                        – Olga
                        Feb 11 '16 at 11:28














                      1390












                      1390








                      1390






                      You can access capturing groups like this:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      var match = myRegexp.exec(myString);
                      console.log(match[1]); // abc





                      And if there are multiple matches you can iterate over them:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      match = myRegexp.exec(myString);
                      while (match != null) {
                      // matched text: match[0]
                      // match start: match.index
                      // capturing group n: match[n]
                      console.log(match[0])
                      match = myRegexp.exec(myString);
                      }








                      share|improve this answer














                      You can access capturing groups like this:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      var match = myRegexp.exec(myString);
                      console.log(match[1]); // abc





                      And if there are multiple matches you can iterate over them:






                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      match = myRegexp.exec(myString);
                      while (match != null) {
                      // matched text: match[0]
                      // match start: match.index
                      // capturing group n: match[n]
                      console.log(match[0])
                      match = myRegexp.exec(myString);
                      }








                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      var match = myRegexp.exec(myString);
                      console.log(match[1]); // abc





                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      var match = myRegexp.exec(myString);
                      console.log(match[1]); // abc





                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      match = myRegexp.exec(myString);
                      while (match != null) {
                      // matched text: match[0]
                      // match start: match.index
                      // capturing group n: match[n]
                      console.log(match[0])
                      match = myRegexp.exec(myString);
                      }





                      var myString = "something format_abc";
                      var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
                      match = myRegexp.exec(myString);
                      while (match != null) {
                      // matched text: match[0]
                      // match start: match.index
                      // capturing group n: match[n]
                      console.log(match[0])
                      match = myRegexp.exec(myString);
                      }






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Aug 16 '16 at 1:42









                      Ruslan López

                      2,80811326




                      2,80811326










                      answered Jan 11 '09 at 7:26









                      CMS

                      586k162841809




                      586k162841809








                      • 94




                        +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
                        – ianaz
                        Aug 28 '12 at 12:06








                      • 5




                        @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
                        – spinningarrow
                        Oct 16 '12 at 7:26






                      • 11




                        Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
                        – JohnAllen
                        Dec 30 '13 at 17:39






                      • 21




                        No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
                        – George Chen
                        Jun 6 '14 at 18:33








                      • 2




                        Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
                        – Olga
                        Feb 11 '16 at 11:28














                      • 94




                        +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
                        – ianaz
                        Aug 28 '12 at 12:06








                      • 5




                        @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
                        – spinningarrow
                        Oct 16 '12 at 7:26






                      • 11




                        Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
                        – JohnAllen
                        Dec 30 '13 at 17:39






                      • 21




                        No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
                        – George Chen
                        Jun 6 '14 at 18:33








                      • 2




                        Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
                        – Olga
                        Feb 11 '16 at 11:28








                      94




                      94




                      +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
                      – ianaz
                      Aug 28 '12 at 12:06






                      +1 Please note that in the second example you should use the RegExp object (not only "/myregexp/"), because it keeps the lastIndex value in the object. Without using the Regexp object it will iterate infinitely
                      – ianaz
                      Aug 28 '12 at 12:06






                      5




                      5




                      @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
                      – spinningarrow
                      Oct 16 '12 at 7:26




                      @ianaz: I don't believe 'tis true? http://jsfiddle.net/weEg9/ seems to work on Chrome, at least.
                      – spinningarrow
                      Oct 16 '12 at 7:26




                      11




                      11




                      Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
                      – JohnAllen
                      Dec 30 '13 at 17:39




                      Why do the above instead of: var match = myString.match(myRegexp); // alert(match[1])?
                      – JohnAllen
                      Dec 30 '13 at 17:39




                      21




                      21




                      No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
                      – George Chen
                      Jun 6 '14 at 18:33






                      No need for explicit "new RegExp", however the infinite loop will occur unless /g is specified
                      – George Chen
                      Jun 6 '14 at 18:33






                      2




                      2




                      Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
                      – Olga
                      Feb 11 '16 at 11:28




                      Another way not to run into infinite loop is to explicetly update string, e.g. string = string.substring(match.index + match[0].length)
                      – Olga
                      Feb 11 '16 at 11:28













                      163














                      Here’s a method you can use to get the n​th capturing group for each match:






                      function getMatches(string, regex, index) {
                      index || (index = 1); // default to the first capturing group
                      var matches = ;
                      var match;
                      while (match = regex.exec(string)) {
                      matches.push(match[index]);
                      }
                      return matches;
                      }


                      // Example :
                      var myString = 'something format_abc something format_def something format_ghi';
                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                      // Get an array containing the first capturing group for every match
                      var matches = getMatches(myString, myRegEx, 1);

                      // Log results
                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                      console.log(matches);








                      share|improve this answer



















                      • 7




                        This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
                        – Rob Evans
                        May 11 '13 at 12:08






                      • 11




                        mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
                        – Druska
                        Sep 4 '13 at 18:45






                      • 2




                        I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
                        – ravishi
                        Nov 21 '13 at 20:00






                      • 4




                        @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
                        – wallacer
                        Oct 29 '14 at 18:34








                      • 3




                        @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
                        – wallacer
                        Nov 12 '14 at 23:44
















                      163














                      Here’s a method you can use to get the n​th capturing group for each match:






                      function getMatches(string, regex, index) {
                      index || (index = 1); // default to the first capturing group
                      var matches = ;
                      var match;
                      while (match = regex.exec(string)) {
                      matches.push(match[index]);
                      }
                      return matches;
                      }


                      // Example :
                      var myString = 'something format_abc something format_def something format_ghi';
                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                      // Get an array containing the first capturing group for every match
                      var matches = getMatches(myString, myRegEx, 1);

                      // Log results
                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                      console.log(matches);








                      share|improve this answer



















                      • 7




                        This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
                        – Rob Evans
                        May 11 '13 at 12:08






                      • 11




                        mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
                        – Druska
                        Sep 4 '13 at 18:45






                      • 2




                        I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
                        – ravishi
                        Nov 21 '13 at 20:00






                      • 4




                        @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
                        – wallacer
                        Oct 29 '14 at 18:34








                      • 3




                        @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
                        – wallacer
                        Nov 12 '14 at 23:44














                      163












                      163








                      163






                      Here’s a method you can use to get the n​th capturing group for each match:






                      function getMatches(string, regex, index) {
                      index || (index = 1); // default to the first capturing group
                      var matches = ;
                      var match;
                      while (match = regex.exec(string)) {
                      matches.push(match[index]);
                      }
                      return matches;
                      }


                      // Example :
                      var myString = 'something format_abc something format_def something format_ghi';
                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                      // Get an array containing the first capturing group for every match
                      var matches = getMatches(myString, myRegEx, 1);

                      // Log results
                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                      console.log(matches);








                      share|improve this answer














                      Here’s a method you can use to get the n​th capturing group for each match:






                      function getMatches(string, regex, index) {
                      index || (index = 1); // default to the first capturing group
                      var matches = ;
                      var match;
                      while (match = regex.exec(string)) {
                      matches.push(match[index]);
                      }
                      return matches;
                      }


                      // Example :
                      var myString = 'something format_abc something format_def something format_ghi';
                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                      // Get an array containing the first capturing group for every match
                      var matches = getMatches(myString, myRegEx, 1);

                      // Log results
                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                      console.log(matches);








                      function getMatches(string, regex, index) {
                      index || (index = 1); // default to the first capturing group
                      var matches = ;
                      var match;
                      while (match = regex.exec(string)) {
                      matches.push(match[index]);
                      }
                      return matches;
                      }


                      // Example :
                      var myString = 'something format_abc something format_def something format_ghi';
                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                      // Get an array containing the first capturing group for every match
                      var matches = getMatches(myString, myRegEx, 1);

                      // Log results
                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                      console.log(matches);





                      function getMatches(string, regex, index) {
                      index || (index = 1); // default to the first capturing group
                      var matches = ;
                      var match;
                      while (match = regex.exec(string)) {
                      matches.push(match[index]);
                      }
                      return matches;
                      }


                      // Example :
                      var myString = 'something format_abc something format_def something format_ghi';
                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                      // Get an array containing the first capturing group for every match
                      var matches = getMatches(myString, myRegEx, 1);

                      // Log results
                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                      console.log(matches);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Apr 17 '15 at 6:52









                      Blowsie

                      34k1375102




                      34k1375102










                      answered Jan 8 '13 at 8:26









                      Mathias Bynens

                      103k39174222




                      103k39174222








                      • 7




                        This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
                        – Rob Evans
                        May 11 '13 at 12:08






                      • 11




                        mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
                        – Druska
                        Sep 4 '13 at 18:45






                      • 2




                        I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
                        – ravishi
                        Nov 21 '13 at 20:00






                      • 4




                        @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
                        – wallacer
                        Oct 29 '14 at 18:34








                      • 3




                        @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
                        – wallacer
                        Nov 12 '14 at 23:44














                      • 7




                        This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
                        – Rob Evans
                        May 11 '13 at 12:08






                      • 11




                        mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
                        – Druska
                        Sep 4 '13 at 18:45






                      • 2




                        I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
                        – ravishi
                        Nov 21 '13 at 20:00






                      • 4




                        @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
                        – wallacer
                        Oct 29 '14 at 18:34








                      • 3




                        @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
                        – wallacer
                        Nov 12 '14 at 23:44








                      7




                      7




                      This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
                      – Rob Evans
                      May 11 '13 at 12:08




                      This a far superior answer to the others because it correctly shows iteration over all matches instead of only getting one.
                      – Rob Evans
                      May 11 '13 at 12:08




                      11




                      11




                      mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
                      – Druska
                      Sep 4 '13 at 18:45




                      mnn is right. This will produce an infinite loop if the 'g' flag is not present. Be very careful with this function.
                      – Druska
                      Sep 4 '13 at 18:45




                      2




                      2




                      I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
                      – ravishi
                      Nov 21 '13 at 20:00




                      I improved this to make it similar to python's re.findall(). It groups up all matches into an array of arrays. It also fixes the global modifier infinite loop issue. jsfiddle.net/ravishi/MbwpV
                      – ravishi
                      Nov 21 '13 at 20:00




                      4




                      4




                      @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
                      – wallacer
                      Oct 29 '14 at 18:34






                      @MichaelMikowski now you've just hidden your infinite loop, but your code will run slow. I'd argue that it's better to have code break in a bad way so you catch it in development. Putting some bs maximum iterations break in is sloppy. Hiding issues instead of fixing their root cause is not the answer.
                      – wallacer
                      Oct 29 '14 at 18:34






                      3




                      3




                      @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
                      – wallacer
                      Nov 12 '14 at 23:44




                      @MichaelMikowski that isn't meaningfully slower when you're not hitting the execution limit. When you are, it's clearly much slower. I'm not saying your code doesn't work, I'm saying that in practice I think it will cause more harm than good. People working in a dev environment will see the code working fine under no load despite doing 10,000 needless executions of some chunk of code. Then they'll push it out to a production environment and wonder why their app goes down under load. In my experience it's better if things break in an obvious way, and earlier in the development cycle.
                      – wallacer
                      Nov 12 '14 at 23:44











                      50

















                      var myString = "something format_abc";
                      var arr = myString.match(/bformat_(.*?)b/);
                      console.log(arr[0] + " " + arr[1]);





                      The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.






                      share|improve this answer



















                      • 1




                        It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
                        – B.F.
                        Apr 22 '15 at 21:09












                      • @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
                        – PhiLho
                        Apr 23 '15 at 7:41












                      • I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
                        – B.F.
                        Apr 23 '15 at 10:43
















                      50

















                      var myString = "something format_abc";
                      var arr = myString.match(/bformat_(.*?)b/);
                      console.log(arr[0] + " " + arr[1]);





                      The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.






                      share|improve this answer



















                      • 1




                        It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
                        – B.F.
                        Apr 22 '15 at 21:09












                      • @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
                        – PhiLho
                        Apr 23 '15 at 7:41












                      • I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
                        – B.F.
                        Apr 23 '15 at 10:43














                      50












                      50








                      50









                      var myString = "something format_abc";
                      var arr = myString.match(/bformat_(.*?)b/);
                      console.log(arr[0] + " " + arr[1]);





                      The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.






                      share|improve this answer

















                      var myString = "something format_abc";
                      var arr = myString.match(/bformat_(.*?)b/);
                      console.log(arr[0] + " " + arr[1]);





                      The b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.






                      var myString = "something format_abc";
                      var arr = myString.match(/bformat_(.*?)b/);
                      console.log(arr[0] + " " + arr[1]);





                      var myString = "something format_abc";
                      var arr = myString.match(/bformat_(.*?)b/);
                      console.log(arr[0] + " " + arr[1]);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 23 '17 at 16:08









                      Michael

                      3,41333756




                      3,41333756










                      answered Jan 11 '09 at 9:10









                      PhiLho

                      34.7k378121




                      34.7k378121








                      • 1




                        It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
                        – B.F.
                        Apr 22 '15 at 21:09












                      • @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
                        – PhiLho
                        Apr 23 '15 at 7:41












                      • I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
                        – B.F.
                        Apr 23 '15 at 10:43














                      • 1




                        It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
                        – B.F.
                        Apr 22 '15 at 21:09












                      • @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
                        – PhiLho
                        Apr 23 '15 at 7:41












                      • I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
                        – B.F.
                        Apr 23 '15 at 10:43








                      1




                      1




                      It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
                      – B.F.
                      Apr 22 '15 at 21:09






                      It's exactly reverse. 'b' delimits words. word= 'w' = [a-zA-Z0-9_] . "format_a_b" is a word.
                      – B.F.
                      Apr 22 '15 at 21:09














                      @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
                      – PhiLho
                      Apr 23 '15 at 7:41






                      @B.F.Honestly, I added "doesn't work on format_a_b" as an after thought 6 years ago, and I don't recall what I meant there... :-) I suppose it meant "doesn't work to capture a only", ie. the first alphabetical part after format_.
                      – PhiLho
                      Apr 23 '15 at 7:41














                      I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
                      – B.F.
                      Apr 23 '15 at 10:43




                      I wanted to say that b(--format_foo/}b do not return "--format_foo/" because "-" and "/" are no word characters. But b(format_a_b)b do return "format_a_b". Right? I refer to your text statement in round brackets. (Did no down vote!)
                      – B.F.
                      Apr 23 '15 at 10:43











                      23














                      In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:



                      var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);


                      After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):



                      var yourstring = 'something format_abc something format_def something format_ghi';

                      var matches = ;
                      yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );


                      After this, I don't think I'm ever going to use .match() for hardly anything ever again.






                      share|improve this answer


























                        23














                        In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:



                        var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);


                        After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):



                        var yourstring = 'something format_abc something format_def something format_ghi';

                        var matches = ;
                        yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );


                        After this, I don't think I'm ever going to use .match() for hardly anything ever again.






                        share|improve this answer
























                          23












                          23








                          23






                          In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:



                          var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);


                          After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):



                          var yourstring = 'something format_abc something format_def something format_ghi';

                          var matches = ;
                          yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );


                          After this, I don't think I'm ever going to use .match() for hardly anything ever again.






                          share|improve this answer












                          In regards to the multi-match parentheses examples above, I was looking for an answer here after not getting what I wanted from:



                          var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);


                          After looking at the slightly convoluted function calls with while and .push() above, it dawned on me that the problem can be solved very elegantly with mystring.replace() instead (the replacing is NOT the point, and isn't even done, the CLEAN, built-in recursive function call option for the second parameter is!):



                          var yourstring = 'something format_abc something format_def something format_ghi';

                          var matches = ;
                          yourstring.replace(/format_([^s]+)/igm, function(m, p1){ matches.push(p1); } );


                          After this, I don't think I'm ever going to use .match() for hardly anything ever again.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jul 17 '14 at 4:53









                          Alexz

                          23123




                          23123























                              16














                              Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.

                              (FF2 went as far as typeof(/pattern/) == 'function')



                              It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.



                              Instead, use either method previously mentioned by others: RegExp#exec or String#match.

                              They offer the same results:



                              var regex = /(?:^|s)format_(.*?)(?:s|$)/;
                              var input = "something format_abc";

                              regex(input); //=> [" format_abc", "abc"]
                              regex.exec(input); //=> [" format_abc", "abc"]
                              input.match(regex); //=> [" format_abc", "abc"]





                              share|improve this answer


























                                16














                                Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.

                                (FF2 went as far as typeof(/pattern/) == 'function')



                                It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.



                                Instead, use either method previously mentioned by others: RegExp#exec or String#match.

                                They offer the same results:



                                var regex = /(?:^|s)format_(.*?)(?:s|$)/;
                                var input = "something format_abc";

                                regex(input); //=> [" format_abc", "abc"]
                                regex.exec(input); //=> [" format_abc", "abc"]
                                input.match(regex); //=> [" format_abc", "abc"]





                                share|improve this answer
























                                  16












                                  16








                                  16






                                  Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.

                                  (FF2 went as far as typeof(/pattern/) == 'function')



                                  It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.



                                  Instead, use either method previously mentioned by others: RegExp#exec or String#match.

                                  They offer the same results:



                                  var regex = /(?:^|s)format_(.*?)(?:s|$)/;
                                  var input = "something format_abc";

                                  regex(input); //=> [" format_abc", "abc"]
                                  regex.exec(input); //=> [" format_abc", "abc"]
                                  input.match(regex); //=> [" format_abc", "abc"]





                                  share|improve this answer












                                  Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.

                                  (FF2 went as far as typeof(/pattern/) == 'function')



                                  It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.



                                  Instead, use either method previously mentioned by others: RegExp#exec or String#match.

                                  They offer the same results:



                                  var regex = /(?:^|s)format_(.*?)(?:s|$)/;
                                  var input = "something format_abc";

                                  regex(input); //=> [" format_abc", "abc"]
                                  regex.exec(input); //=> [" format_abc", "abc"]
                                  input.match(regex); //=> [" format_abc", "abc"]






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jan 11 '09 at 12:55









                                  Jonathan Lonowski

                                  92.3k25167181




                                  92.3k25167181























                                      12














                                      Last but not least, I found one line of code that worked fine for me (JS ES6):






                                      let reg = /#([S]+)/igm; // Get hashtags.
                                      let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

                                      let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
                                      console.log(matches);





                                      This will return:



                                      ['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']





                                      share|improve this answer



















                                      • 1




                                        this is works well except when match can't find anything then map doesn't work.
                                        – MBehtemam
                                        Nov 25 '17 at 11:23
















                                      12














                                      Last but not least, I found one line of code that worked fine for me (JS ES6):






                                      let reg = /#([S]+)/igm; // Get hashtags.
                                      let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

                                      let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
                                      console.log(matches);





                                      This will return:



                                      ['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']





                                      share|improve this answer



















                                      • 1




                                        this is works well except when match can't find anything then map doesn't work.
                                        – MBehtemam
                                        Nov 25 '17 at 11:23














                                      12












                                      12








                                      12






                                      Last but not least, I found one line of code that worked fine for me (JS ES6):






                                      let reg = /#([S]+)/igm; // Get hashtags.
                                      let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

                                      let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
                                      console.log(matches);





                                      This will return:



                                      ['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']





                                      share|improve this answer














                                      Last but not least, I found one line of code that worked fine for me (JS ES6):






                                      let reg = /#([S]+)/igm; // Get hashtags.
                                      let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

                                      let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
                                      console.log(matches);





                                      This will return:



                                      ['fiestasdefindeaño', 'PadreHijo', 'buenosmomentos', 'france', 'paris']





                                      let reg = /#([S]+)/igm; // Get hashtags.
                                      let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

                                      let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
                                      console.log(matches);





                                      let reg = /#([S]+)/igm; // Get hashtags.
                                      let string = 'mi alegría es total! ✌🙌n#fiestasdefindeaño #PadreHijo #buenosmomentos #france #paris';

                                      let matches = (string.match(reg) || ).map(e => e.replace(reg, '$1'));
                                      console.log(matches);






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Dec 21 at 14:54

























                                      answered Jan 3 '17 at 14:40









                                      Sebastien H.

                                      3,21021723




                                      3,21021723








                                      • 1




                                        this is works well except when match can't find anything then map doesn't work.
                                        – MBehtemam
                                        Nov 25 '17 at 11:23














                                      • 1




                                        this is works well except when match can't find anything then map doesn't work.
                                        – MBehtemam
                                        Nov 25 '17 at 11:23








                                      1




                                      1




                                      this is works well except when match can't find anything then map doesn't work.
                                      – MBehtemam
                                      Nov 25 '17 at 11:23




                                      this is works well except when match can't find anything then map doesn't work.
                                      – MBehtemam
                                      Nov 25 '17 at 11:23











                                      11














                                      Terminology used in this answer:





                                      • Match indicates the result of running your RegEx pattern against your string like so: someString.match(regexPattern).


                                      • Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.


                                      • Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.*?)/g, where (.*?) would be a matched group.) These reside within matched patterns.


                                      Description



                                      To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.



                                      Code examples



                                      Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.



                                      Concise versions (less code, more syntactic sugar)



                                      These are less performant since they basically implement a forEach-loop instead of the faster for-loop.



                                      // Concise ES6/ES2015 syntax
                                      const searchString =
                                      (string, pattern) =>
                                      string
                                      .match(new RegExp(pattern.source, pattern.flags))
                                      .map(match =>
                                      new RegExp(pattern.source, pattern.flags)
                                      .exec(match));

                                      // Or if you will, with ES5 syntax
                                      function searchString(string, pattern) {
                                      return string
                                      .match(new RegExp(pattern.source, pattern.flags))
                                      .map(match =>
                                      new RegExp(pattern.source, pattern.flags)
                                      .exec(match));
                                      }

                                      let string = "something format_abc",
                                      pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                      let result = searchString(string, pattern);
                                      // [[" format_abc", "abc"], null]
                                      // The trailing `null` disappears if you add the `global` flag


                                      Performant versions (more code, less syntactic sugar)



                                      // Performant ES6/ES2015 syntax
                                      const searchString = (string, pattern) => {
                                      let result = ;

                                      const matches = string.match(new RegExp(pattern.source, pattern.flags));

                                      for (let i = 0; i < matches.length; i++) {
                                      result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                      }

                                      return result;
                                      };

                                      // Same thing, but with ES5 syntax
                                      function searchString(string, pattern) {
                                      var result = ;

                                      var matches = string.match(new RegExp(pattern.source, pattern.flags));

                                      for (var i = 0; i < matches.length; i++) {
                                      result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                      }

                                      return result;
                                      }

                                      let string = "something format_abc",
                                      pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                      let result = searchString(string, pattern);
                                      // [[" format_abc", "abc"], null]
                                      // The trailing `null` disappears if you add the `global` flag


                                      I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.






                                      share|improve this answer


























                                        11














                                        Terminology used in this answer:





                                        • Match indicates the result of running your RegEx pattern against your string like so: someString.match(regexPattern).


                                        • Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.


                                        • Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.*?)/g, where (.*?) would be a matched group.) These reside within matched patterns.


                                        Description



                                        To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.



                                        Code examples



                                        Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.



                                        Concise versions (less code, more syntactic sugar)



                                        These are less performant since they basically implement a forEach-loop instead of the faster for-loop.



                                        // Concise ES6/ES2015 syntax
                                        const searchString =
                                        (string, pattern) =>
                                        string
                                        .match(new RegExp(pattern.source, pattern.flags))
                                        .map(match =>
                                        new RegExp(pattern.source, pattern.flags)
                                        .exec(match));

                                        // Or if you will, with ES5 syntax
                                        function searchString(string, pattern) {
                                        return string
                                        .match(new RegExp(pattern.source, pattern.flags))
                                        .map(match =>
                                        new RegExp(pattern.source, pattern.flags)
                                        .exec(match));
                                        }

                                        let string = "something format_abc",
                                        pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                        let result = searchString(string, pattern);
                                        // [[" format_abc", "abc"], null]
                                        // The trailing `null` disappears if you add the `global` flag


                                        Performant versions (more code, less syntactic sugar)



                                        // Performant ES6/ES2015 syntax
                                        const searchString = (string, pattern) => {
                                        let result = ;

                                        const matches = string.match(new RegExp(pattern.source, pattern.flags));

                                        for (let i = 0; i < matches.length; i++) {
                                        result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                        }

                                        return result;
                                        };

                                        // Same thing, but with ES5 syntax
                                        function searchString(string, pattern) {
                                        var result = ;

                                        var matches = string.match(new RegExp(pattern.source, pattern.flags));

                                        for (var i = 0; i < matches.length; i++) {
                                        result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                        }

                                        return result;
                                        }

                                        let string = "something format_abc",
                                        pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                        let result = searchString(string, pattern);
                                        // [[" format_abc", "abc"], null]
                                        // The trailing `null` disappears if you add the `global` flag


                                        I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.






                                        share|improve this answer
























                                          11












                                          11








                                          11






                                          Terminology used in this answer:





                                          • Match indicates the result of running your RegEx pattern against your string like so: someString.match(regexPattern).


                                          • Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.


                                          • Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.*?)/g, where (.*?) would be a matched group.) These reside within matched patterns.


                                          Description



                                          To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.



                                          Code examples



                                          Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.



                                          Concise versions (less code, more syntactic sugar)



                                          These are less performant since they basically implement a forEach-loop instead of the faster for-loop.



                                          // Concise ES6/ES2015 syntax
                                          const searchString =
                                          (string, pattern) =>
                                          string
                                          .match(new RegExp(pattern.source, pattern.flags))
                                          .map(match =>
                                          new RegExp(pattern.source, pattern.flags)
                                          .exec(match));

                                          // Or if you will, with ES5 syntax
                                          function searchString(string, pattern) {
                                          return string
                                          .match(new RegExp(pattern.source, pattern.flags))
                                          .map(match =>
                                          new RegExp(pattern.source, pattern.flags)
                                          .exec(match));
                                          }

                                          let string = "something format_abc",
                                          pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                          let result = searchString(string, pattern);
                                          // [[" format_abc", "abc"], null]
                                          // The trailing `null` disappears if you add the `global` flag


                                          Performant versions (more code, less syntactic sugar)



                                          // Performant ES6/ES2015 syntax
                                          const searchString = (string, pattern) => {
                                          let result = ;

                                          const matches = string.match(new RegExp(pattern.source, pattern.flags));

                                          for (let i = 0; i < matches.length; i++) {
                                          result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                          }

                                          return result;
                                          };

                                          // Same thing, but with ES5 syntax
                                          function searchString(string, pattern) {
                                          var result = ;

                                          var matches = string.match(new RegExp(pattern.source, pattern.flags));

                                          for (var i = 0; i < matches.length; i++) {
                                          result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                          }

                                          return result;
                                          }

                                          let string = "something format_abc",
                                          pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                          let result = searchString(string, pattern);
                                          // [[" format_abc", "abc"], null]
                                          // The trailing `null` disappears if you add the `global` flag


                                          I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.






                                          share|improve this answer












                                          Terminology used in this answer:





                                          • Match indicates the result of running your RegEx pattern against your string like so: someString.match(regexPattern).


                                          • Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.


                                          • Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.*?)/g, where (.*?) would be a matched group.) These reside within matched patterns.


                                          Description



                                          To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator function – it stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.



                                          Code examples



                                          Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.



                                          Concise versions (less code, more syntactic sugar)



                                          These are less performant since they basically implement a forEach-loop instead of the faster for-loop.



                                          // Concise ES6/ES2015 syntax
                                          const searchString =
                                          (string, pattern) =>
                                          string
                                          .match(new RegExp(pattern.source, pattern.flags))
                                          .map(match =>
                                          new RegExp(pattern.source, pattern.flags)
                                          .exec(match));

                                          // Or if you will, with ES5 syntax
                                          function searchString(string, pattern) {
                                          return string
                                          .match(new RegExp(pattern.source, pattern.flags))
                                          .map(match =>
                                          new RegExp(pattern.source, pattern.flags)
                                          .exec(match));
                                          }

                                          let string = "something format_abc",
                                          pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                          let result = searchString(string, pattern);
                                          // [[" format_abc", "abc"], null]
                                          // The trailing `null` disappears if you add the `global` flag


                                          Performant versions (more code, less syntactic sugar)



                                          // Performant ES6/ES2015 syntax
                                          const searchString = (string, pattern) => {
                                          let result = ;

                                          const matches = string.match(new RegExp(pattern.source, pattern.flags));

                                          for (let i = 0; i < matches.length; i++) {
                                          result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                          }

                                          return result;
                                          };

                                          // Same thing, but with ES5 syntax
                                          function searchString(string, pattern) {
                                          var result = ;

                                          var matches = string.match(new RegExp(pattern.source, pattern.flags));

                                          for (var i = 0; i < matches.length; i++) {
                                          result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
                                          }

                                          return result;
                                          }

                                          let string = "something format_abc",
                                          pattern = /(?:^|s)format_(.*?)(?:s|$)/;

                                          let result = searchString(string, pattern);
                                          // [[" format_abc", "abc"], null]
                                          // The trailing `null` disappears if you add the `global` flag


                                          I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Aug 23 '17 at 22:36









                                          Daniel Hallgren

                                          337311




                                          337311























                                              9














                                              There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.



                                              var str = "This is cool";
                                              var matches = str.match(/(This is)( cool)$/);
                                              console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...


                                              Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!






                                              share|improve this answer



















                                              • 1




                                                This works and feels more natural.
                                                – Vidar
                                                May 29 at 11:54






                                              • 1




                                                Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                                                – Shadymilkman01
                                                Sep 13 at 22:00
















                                              9














                                              There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.



                                              var str = "This is cool";
                                              var matches = str.match(/(This is)( cool)$/);
                                              console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...


                                              Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!






                                              share|improve this answer



















                                              • 1




                                                This works and feels more natural.
                                                – Vidar
                                                May 29 at 11:54






                                              • 1




                                                Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                                                – Shadymilkman01
                                                Sep 13 at 22:00














                                              9












                                              9








                                              9






                                              There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.



                                              var str = "This is cool";
                                              var matches = str.match(/(This is)( cool)$/);
                                              console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...


                                              Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!






                                              share|improve this answer














                                              There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.



                                              var str = "This is cool";
                                              var matches = str.match(/(This is)( cool)$/);
                                              console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...


                                              Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Aug 11 '17 at 18:58

























                                              answered Jun 19 '17 at 19:47









                                              Andre Carneiro

                                              367213




                                              367213








                                              • 1




                                                This works and feels more natural.
                                                – Vidar
                                                May 29 at 11:54






                                              • 1




                                                Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                                                – Shadymilkman01
                                                Sep 13 at 22:00














                                              • 1




                                                This works and feels more natural.
                                                – Vidar
                                                May 29 at 11:54






                                              • 1




                                                Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                                                – Shadymilkman01
                                                Sep 13 at 22:00








                                              1




                                              1




                                              This works and feels more natural.
                                              – Vidar
                                              May 29 at 11:54




                                              This works and feels more natural.
                                              – Vidar
                                              May 29 at 11:54




                                              1




                                              1




                                              Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                                              – Shadymilkman01
                                              Sep 13 at 22:00




                                              Without the global flag this returns all the matches, with it, you'll only get one big one so watch out for that.
                                              – Shadymilkman01
                                              Sep 13 at 22:00











                                              7














                                              A one liner that is practical only if you have a single pair of parenthesis:



                                              while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};





                                              share|improve this answer

















                                              • 3




                                                Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                                                – willlma
                                                Apr 6 '17 at 18:44












                                              • @willlma Yep!..
                                                – Nabil Kadimi
                                                May 23 '17 at 20:00
















                                              7














                                              A one liner that is practical only if you have a single pair of parenthesis:



                                              while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};





                                              share|improve this answer

















                                              • 3




                                                Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                                                – willlma
                                                Apr 6 '17 at 18:44












                                              • @willlma Yep!..
                                                – Nabil Kadimi
                                                May 23 '17 at 20:00














                                              7












                                              7








                                              7






                                              A one liner that is practical only if you have a single pair of parenthesis:



                                              while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};





                                              share|improve this answer












                                              A one liner that is practical only if you have a single pair of parenthesis:



                                              while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Jul 12 '14 at 15:41









                                              Nabil Kadimi

                                              7,32623147




                                              7,32623147








                                              • 3




                                                Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                                                – willlma
                                                Apr 6 '17 at 18:44












                                              • @willlma Yep!..
                                                – Nabil Kadimi
                                                May 23 '17 at 20:00














                                              • 3




                                                Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                                                – willlma
                                                Apr 6 '17 at 18:44












                                              • @willlma Yep!..
                                                – Nabil Kadimi
                                                May 23 '17 at 20:00








                                              3




                                              3




                                              Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                                              – willlma
                                              Apr 6 '17 at 18:44






                                              Why not while (match = myRegex.exec(myStr)) matches.push(match[1])
                                              – willlma
                                              Apr 6 '17 at 18:44














                                              @willlma Yep!..
                                              – Nabil Kadimi
                                              May 23 '17 at 20:00




                                              @willlma Yep!..
                                              – Nabil Kadimi
                                              May 23 '17 at 20:00











                                              5














                                              Using your code:



                                              console.log(arr[1]);  // prints: abc
                                              console.log(arr[0]); // prints: format_abc


                                              Edit: Safari 3, if it matters.






                                              share|improve this answer


























                                                5














                                                Using your code:



                                                console.log(arr[1]);  // prints: abc
                                                console.log(arr[0]); // prints: format_abc


                                                Edit: Safari 3, if it matters.






                                                share|improve this answer
























                                                  5












                                                  5








                                                  5






                                                  Using your code:



                                                  console.log(arr[1]);  // prints: abc
                                                  console.log(arr[0]); // prints: format_abc


                                                  Edit: Safari 3, if it matters.






                                                  share|improve this answer












                                                  Using your code:



                                                  console.log(arr[1]);  // prints: abc
                                                  console.log(arr[0]); // prints: format_abc


                                                  Edit: Safari 3, if it matters.







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jan 11 '09 at 7:27









                                                  eyelidlessness

                                                  50.1k118190




                                                  50.1k118190























                                                      5

















                                                      function getMatches(string, regex, index) {
                                                      index || (index = 1); // default to the first capturing group
                                                      var matches = ;
                                                      var match;
                                                      while (match = regex.exec(string)) {
                                                      matches.push(match[index]);
                                                      }
                                                      return matches;
                                                      }


                                                      // Example :
                                                      var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                                                      var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                                                      // Get an array containing the first capturing group for every match
                                                      var matches = getMatches(myString, myRegEx, 1);

                                                      // Log results
                                                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                      console.log(matches);








                                                      function getMatches(string, regex, index) {
                                                      index || (index = 1); // default to the first capturing group
                                                      var matches = ;
                                                      var match;
                                                      while (match = regex.exec(string)) {
                                                      matches.push(match[index]);
                                                      }
                                                      return matches;
                                                      }


                                                      // Example :
                                                      var myString = 'something format_abc something format_def something format_ghi';
                                                      var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                                                      // Get an array containing the first capturing group for every match
                                                      var matches = getMatches(myString, myRegEx, 1);

                                                      // Log results
                                                      document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                      console.log(matches);








                                                      share|improve this answer




























                                                        5

















                                                        function getMatches(string, regex, index) {
                                                        index || (index = 1); // default to the first capturing group
                                                        var matches = ;
                                                        var match;
                                                        while (match = regex.exec(string)) {
                                                        matches.push(match[index]);
                                                        }
                                                        return matches;
                                                        }


                                                        // Example :
                                                        var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                                                        var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                                                        // Get an array containing the first capturing group for every match
                                                        var matches = getMatches(myString, myRegEx, 1);

                                                        // Log results
                                                        document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                        console.log(matches);








                                                        function getMatches(string, regex, index) {
                                                        index || (index = 1); // default to the first capturing group
                                                        var matches = ;
                                                        var match;
                                                        while (match = regex.exec(string)) {
                                                        matches.push(match[index]);
                                                        }
                                                        return matches;
                                                        }


                                                        // Example :
                                                        var myString = 'something format_abc something format_def something format_ghi';
                                                        var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                                                        // Get an array containing the first capturing group for every match
                                                        var matches = getMatches(myString, myRegEx, 1);

                                                        // Log results
                                                        document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                        console.log(matches);








                                                        share|improve this answer


























                                                          5












                                                          5








                                                          5









                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                                                          var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);








                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'something format_abc something format_def something format_ghi';
                                                          var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);








                                                          share|improve this answer

















                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                                                          var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);








                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'something format_abc something format_def something format_ghi';
                                                          var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);








                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                                                          var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);





                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';
                                                          var myRegEx = /clear bal.+?(d+.?d{2})/gi;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);





                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'something format_abc something format_def something format_ghi';
                                                          var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);





                                                          function getMatches(string, regex, index) {
                                                          index || (index = 1); // default to the first capturing group
                                                          var matches = ;
                                                          var match;
                                                          while (match = regex.exec(string)) {
                                                          matches.push(match[index]);
                                                          }
                                                          return matches;
                                                          }


                                                          // Example :
                                                          var myString = 'something format_abc something format_def something format_ghi';
                                                          var myRegEx = /(?:^|s)format_(.*?)(?:s|$)/g;

                                                          // Get an array containing the first capturing group for every match
                                                          var matches = getMatches(myString, myRegEx, 1);

                                                          // Log results
                                                          document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
                                                          console.log(matches);






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jun 22 '17 at 20:38









                                                          Nisse Engström

                                                          4,10892034




                                                          4,10892034










                                                          answered Nov 25 '16 at 9:46









                                                          Jack

                                                          6617




                                                          6617























                                                              2














                                                              Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:



                                                              /bformat_(.*?)b/


                                                              (But, of course, I'm not sure because I don't know the context of the regex.)






                                                              share|improve this answer























                                                              • it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                                                                – nickf
                                                                Jan 11 '09 at 12:04










                                                              • Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                                                                – PEZ
                                                                Jan 11 '09 at 12:21
















                                                              2














                                                              Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:



                                                              /bformat_(.*?)b/


                                                              (But, of course, I'm not sure because I don't know the context of the regex.)






                                                              share|improve this answer























                                                              • it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                                                                – nickf
                                                                Jan 11 '09 at 12:04










                                                              • Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                                                                – PEZ
                                                                Jan 11 '09 at 12:21














                                                              2












                                                              2








                                                              2






                                                              Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:



                                                              /bformat_(.*?)b/


                                                              (But, of course, I'm not sure because I don't know the context of the regex.)






                                                              share|improve this answer














                                                              Your code works for me (FF3 on Mac) even if I agree with PhiLo that the regex should probably be:



                                                              /bformat_(.*?)b/


                                                              (But, of course, I'm not sure because I don't know the context of the regex.)







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited May 23 '17 at 12:34









                                                              Community

                                                              11




                                                              11










                                                              answered Jan 11 '09 at 10:39









                                                              PEZ

                                                              13.5k53457




                                                              13.5k53457












                                                              • it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                                                                – nickf
                                                                Jan 11 '09 at 12:04










                                                              • Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                                                                – PEZ
                                                                Jan 11 '09 at 12:21


















                                                              • it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                                                                – nickf
                                                                Jan 11 '09 at 12:04










                                                              • Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                                                                – PEZ
                                                                Jan 11 '09 at 12:21
















                                                              it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                                                              – nickf
                                                              Jan 11 '09 at 12:04




                                                              it's a space-separated list so I figured s would be fine. strange that that code wasn't working for me (FF3 Vista)
                                                              – nickf
                                                              Jan 11 '09 at 12:04












                                                              Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                                                              – PEZ
                                                              Jan 11 '09 at 12:21




                                                              Yes, truly strange. Have you tried it on its own in the Firebug console? From an otherwise empty page I mean.
                                                              – PEZ
                                                              Jan 11 '09 at 12:21











                                                              1














                                                              /*Regex function for extracting object from "window.location.search" string.
                                                              */

                                                              var search = "?a=3&b=4&c=7"; // Example search string

                                                              var getSearchObj = function (searchString) {

                                                              var match, key, value, obj = {};
                                                              var pattern = /(w+)=(w+)/g;
                                                              var search = searchString.substr(1); // Remove '?'

                                                              while (match = pattern.exec(search)) {
                                                              obj[match[0].split('=')[0]] = match[0].split('=')[1];
                                                              }

                                                              return obj;

                                                              };

                                                              console.log(getSearchObj(search));





                                                              share|improve this answer


























                                                                1














                                                                /*Regex function for extracting object from "window.location.search" string.
                                                                */

                                                                var search = "?a=3&b=4&c=7"; // Example search string

                                                                var getSearchObj = function (searchString) {

                                                                var match, key, value, obj = {};
                                                                var pattern = /(w+)=(w+)/g;
                                                                var search = searchString.substr(1); // Remove '?'

                                                                while (match = pattern.exec(search)) {
                                                                obj[match[0].split('=')[0]] = match[0].split('=')[1];
                                                                }

                                                                return obj;

                                                                };

                                                                console.log(getSearchObj(search));





                                                                share|improve this answer
























                                                                  1












                                                                  1








                                                                  1






                                                                  /*Regex function for extracting object from "window.location.search" string.
                                                                  */

                                                                  var search = "?a=3&b=4&c=7"; // Example search string

                                                                  var getSearchObj = function (searchString) {

                                                                  var match, key, value, obj = {};
                                                                  var pattern = /(w+)=(w+)/g;
                                                                  var search = searchString.substr(1); // Remove '?'

                                                                  while (match = pattern.exec(search)) {
                                                                  obj[match[0].split('=')[0]] = match[0].split('=')[1];
                                                                  }

                                                                  return obj;

                                                                  };

                                                                  console.log(getSearchObj(search));





                                                                  share|improve this answer












                                                                  /*Regex function for extracting object from "window.location.search" string.
                                                                  */

                                                                  var search = "?a=3&b=4&c=7"; // Example search string

                                                                  var getSearchObj = function (searchString) {

                                                                  var match, key, value, obj = {};
                                                                  var pattern = /(w+)=(w+)/g;
                                                                  var search = searchString.substr(1); // Remove '?'

                                                                  while (match = pattern.exec(search)) {
                                                                  obj[match[0].split('=')[0]] = match[0].split('=')[1];
                                                                  }

                                                                  return obj;

                                                                  };

                                                                  console.log(getSearchObj(search));






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Jun 27 '15 at 18:47









                                                                  Pawel Kwiecien

                                                                  212




                                                                  212






























                                                                      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%2f432493%2fhow-do-you-access-the-matched-groups-in-a-javascript-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

                                                                      Tonle Sap (See)

                                                                      I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                                                                      Guatemaltekische Davis-Cup-Mannschaft