Javascript replace with reference to matched group?












185















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





























    185















    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



























      185












      185








      185


      38






      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 '18 at 4:00









      K48

      5,51093992




      5,51093992










      asked Aug 5 '09 at 17:48









      Sinan TaifourSinan Taifour

      6,78122529




      6,78122529
























          3 Answers
          3






          active

          oldest

          votes


















          307














          "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





















          26














          You can use replace instead of gsub.



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





          share|improve this answer



















          • 16





            You can remove the backslash.

            – CalculatorFeline
            Apr 30 '16 at 0:15





















          1














          For the replacement string and the replacement pattern as specified by $.
          here a resume:



          enter image description here



          link to doc : here



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




          Note:



          If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.






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

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            307














            "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


















            307














            "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
















            307












            307








            307







            "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,95573163




            2,95573163










            answered Aug 5 '09 at 17:51









            airportyhairportyh

            13.1k95269




            13.1k95269








            • 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















            26














            You can use replace instead of gsub.



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





            share|improve this answer



















            • 16





              You can remove the backslash.

              – CalculatorFeline
              Apr 30 '16 at 0:15


















            26














            You can use replace instead of gsub.



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





            share|improve this answer



















            • 16





              You can remove the backslash.

              – CalculatorFeline
              Apr 30 '16 at 0:15
















            26












            26








            26







            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









            EifionEifion

            3,9162225




            3,9162225








            • 16





              You can remove the backslash.

              – CalculatorFeline
              Apr 30 '16 at 0:15
















            • 16





              You can remove the backslash.

              – CalculatorFeline
              Apr 30 '16 at 0:15










            16




            16





            You can remove the backslash.

            – CalculatorFeline
            Apr 30 '16 at 0:15







            You can remove the backslash.

            – CalculatorFeline
            Apr 30 '16 at 0:15













            1














            For the replacement string and the replacement pattern as specified by $.
            here a resume:



            enter image description here



            link to doc : here



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




            Note:



            If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.






            share|improve this answer




























              1














              For the replacement string and the replacement pattern as specified by $.
              here a resume:



              enter image description here



              link to doc : here



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




              Note:



              If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.






              share|improve this answer


























                1












                1








                1







                For the replacement string and the replacement pattern as specified by $.
                here a resume:



                enter image description here



                link to doc : here



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




                Note:



                If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.






                share|improve this answer













                For the replacement string and the replacement pattern as specified by $.
                here a resume:



                enter image description here



                link to doc : here



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




                Note:



                If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 2 at 13:05









                Mohamed AllalMohamed Allal

                2,2211321




                2,2211321






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


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

                    But avoid



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

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


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




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%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

                    Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                    ComboBox Display Member on multiple fields

                    Is it possible to collect Nectar points via Trainline?