Javascript replace with reference to matched group?












180














I have a string, such as hello _there_. I'd like to replace the two underscores with <div> and </div> respectively, using JavaScript. The output would (therefore) look like hello <div>there</div>. The string might contain multiple pairs of underscores.



What I am looking for is a way to either run a function on each match, the way Ruby does it:



"hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }


Or be able to reference a matched group, again the way it can be done in ruby:



"hello _there_".gsub(/_(.*?)_/, "<div>\1</div>")


Any ideas or suggestions?










share|improve this question





























    180














    I have a string, such as hello _there_. I'd like to replace the two underscores with <div> and </div> respectively, using JavaScript. The output would (therefore) look like hello <div>there</div>. The string might contain multiple pairs of underscores.



    What I am looking for is a way to either run a function on each match, the way Ruby does it:



    "hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }


    Or be able to reference a matched group, again the way it can be done in ruby:



    "hello _there_".gsub(/_(.*?)_/, "<div>\1</div>")


    Any ideas or suggestions?










    share|improve this question



























      180












      180








      180


      36





      I have a string, such as hello _there_. I'd like to replace the two underscores with <div> and </div> respectively, using JavaScript. The output would (therefore) look like hello <div>there</div>. The string might contain multiple pairs of underscores.



      What I am looking for is a way to either run a function on each match, the way Ruby does it:



      "hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }


      Or be able to reference a matched group, again the way it can be done in ruby:



      "hello _there_".gsub(/_(.*?)_/, "<div>\1</div>")


      Any ideas or suggestions?










      share|improve this question















      I have a string, such as hello _there_. I'd like to replace the two underscores with <div> and </div> respectively, using JavaScript. The output would (therefore) look like hello <div>there</div>. The string might contain multiple pairs of underscores.



      What I am looking for is a way to either run a function on each match, the way Ruby does it:



      "hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }


      Or be able to reference a matched group, again the way it can be done in ruby:



      "hello _there_".gsub(/_(.*?)_/, "<div>\1</div>")


      Any ideas or suggestions?







      javascript regex






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 3 at 4:00









      K48

      5,37993990




      5,37993990










      asked Aug 5 '09 at 17:48









      Sinan Taifour

      6,70622529




      6,70622529
























          2 Answers
          2






          active

          oldest

          votes


















          303














          "hello _there_".replace(/_(.*?)_/, function(a, b){
          return '<div>' + b + '</div>';
          })


          Oh, or you could also:



          "hello _there_".replace(/_(.*?)_/, "<div>$1</div>")





          share|improve this answer



















          • 5




            Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
            – daveloyall
            Jun 11 '14 at 19:43






          • 6




            @daveloyall es5.github.io/#x15.5.4.11
            – Philipp
            Jun 13 '14 at 7:37






          • 3




            replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
            – daveloyall
            Jun 13 '14 at 20:36






          • 3




            i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
            – jsh
            Oct 1 '15 at 7:55






          • 1




            @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
            – Stewart
            Jun 23 '16 at 9:55





















          25














          You can use replace instead of gsub.



          "hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")





          share|improve this answer

















          • 15




            You can remove the backslash.
            – CalculatorFeline
            Apr 30 '16 at 0:15













          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%2f1234712%2fjavascript-replace-with-reference-to-matched-group%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          303














          "hello _there_".replace(/_(.*?)_/, function(a, b){
          return '<div>' + b + '</div>';
          })


          Oh, or you could also:



          "hello _there_".replace(/_(.*?)_/, "<div>$1</div>")





          share|improve this answer



















          • 5




            Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
            – daveloyall
            Jun 11 '14 at 19:43






          • 6




            @daveloyall es5.github.io/#x15.5.4.11
            – Philipp
            Jun 13 '14 at 7:37






          • 3




            replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
            – daveloyall
            Jun 13 '14 at 20:36






          • 3




            i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
            – jsh
            Oct 1 '15 at 7:55






          • 1




            @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
            – Stewart
            Jun 23 '16 at 9:55


















          303














          "hello _there_".replace(/_(.*?)_/, function(a, b){
          return '<div>' + b + '</div>';
          })


          Oh, or you could also:



          "hello _there_".replace(/_(.*?)_/, "<div>$1</div>")





          share|improve this answer



















          • 5




            Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
            – daveloyall
            Jun 11 '14 at 19:43






          • 6




            @daveloyall es5.github.io/#x15.5.4.11
            – Philipp
            Jun 13 '14 at 7:37






          • 3




            replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
            – daveloyall
            Jun 13 '14 at 20:36






          • 3




            i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
            – jsh
            Oct 1 '15 at 7:55






          • 1




            @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
            – Stewart
            Jun 23 '16 at 9:55
















          303












          303








          303






          "hello _there_".replace(/_(.*?)_/, function(a, b){
          return '<div>' + b + '</div>';
          })


          Oh, or you could also:



          "hello _there_".replace(/_(.*?)_/, "<div>$1</div>")





          share|improve this answer














          "hello _there_".replace(/_(.*?)_/, function(a, b){
          return '<div>' + b + '</div>';
          })


          Oh, or you could also:



          "hello _there_".replace(/_(.*?)_/, "<div>$1</div>")






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '17 at 7:21









          Rand Random

          2,90573162




          2,90573162










          answered Aug 5 '09 at 17:51









          airportyh

          13k95169




          13k95169








          • 5




            Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
            – daveloyall
            Jun 11 '14 at 19:43






          • 6




            @daveloyall es5.github.io/#x15.5.4.11
            – Philipp
            Jun 13 '14 at 7:37






          • 3




            replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
            – daveloyall
            Jun 13 '14 at 20:36






          • 3




            i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
            – jsh
            Oct 1 '15 at 7:55






          • 1




            @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
            – Stewart
            Jun 23 '16 at 9:55
















          • 5




            Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
            – daveloyall
            Jun 11 '14 at 19:43






          • 6




            @daveloyall es5.github.io/#x15.5.4.11
            – Philipp
            Jun 13 '14 at 7:37






          • 3




            replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
            – daveloyall
            Jun 13 '14 at 20:36






          • 3




            i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
            – jsh
            Oct 1 '15 at 7:55






          • 1




            @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
            – Stewart
            Jun 23 '16 at 9:55










          5




          5




          Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
          – daveloyall
          Jun 11 '14 at 19:43




          Does Javascript use $1 instead of 1? Would someone provide a link to documentation?
          – daveloyall
          Jun 11 '14 at 19:43




          6




          6




          @daveloyall es5.github.io/#x15.5.4.11
          – Philipp
          Jun 13 '14 at 7:37




          @daveloyall es5.github.io/#x15.5.4.11
          – Philipp
          Jun 13 '14 at 7:37




          3




          3




          replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
          – daveloyall
          Jun 13 '14 at 20:36




          replacementValue can be a function and it is passed different arguments based on the catch groups? Amazing!
          – daveloyall
          Jun 13 '14 at 20:36




          3




          3




          i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
          – jsh
          Oct 1 '15 at 7:55




          i found 1 worked but $1 did NOT although I am using the RegExp variation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
          – jsh
          Oct 1 '15 at 7:55




          1




          1




          @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
          – Stewart
          Jun 23 '16 at 9:55






          @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: "hello _there_".replace(/_(.*?)_/, /<div>1</div>/).
          – Stewart
          Jun 23 '16 at 9:55















          25














          You can use replace instead of gsub.



          "hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")





          share|improve this answer

















          • 15




            You can remove the backslash.
            – CalculatorFeline
            Apr 30 '16 at 0:15


















          25














          You can use replace instead of gsub.



          "hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")





          share|improve this answer

















          • 15




            You can remove the backslash.
            – CalculatorFeline
            Apr 30 '16 at 0:15
















          25












          25








          25






          You can use replace instead of gsub.



          "hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")





          share|improve this answer












          You can use replace instead of gsub.



          "hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 5 '09 at 17:52









          Eifion

          3,8562224




          3,8562224








          • 15




            You can remove the backslash.
            – CalculatorFeline
            Apr 30 '16 at 0:15
















          • 15




            You can remove the backslash.
            – CalculatorFeline
            Apr 30 '16 at 0:15










          15




          15




          You can remove the backslash.
          – CalculatorFeline
          Apr 30 '16 at 0:15






          You can remove the backslash.
          – CalculatorFeline
          Apr 30 '16 at 0:15




















          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%2f1234712%2fjavascript-replace-with-reference-to-matched-group%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

          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

          Alcedinidae

          Origin of the phrase “under your belt”?