regex: replace dynamically a searched word Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!A comprehensive regex for phone number validationHow can I merge properties of two JavaScript objects dynamically?Event binding on dynamically created elements?Regular expression to match a line that doesn't contain a wordInteractive search/replace regex in Vim?Converting user input string to regular expressionHow to replace all occurrences of a string in JavaScriptHow to negate specific word in regex?RegEx match open tags except XHTML self-contained tagsPython string.replace regular expression

What to do with repeated rejections for phd position

How does light 'choose' between wave and particle behaviour?

Intuitive explanation of the rank-nullity theorem

How long can equipment go unused before powering up runs the risk of damage?

How many morphisms from 1 to 1+1 can there be?

preposition before coffee

Misunderstanding of Sylow theory

Do wooden building fires get hotter than 600°C?

Lagrange four-squares theorem --- deterministic complexity

How does Belgium enforce obligatory attendance in elections?

How could we fake a moon landing now?

A letter with no particular backstory

How to identify unknown coordinate type and convert to lat/lon?

How often does castling occur in grandmaster games?

What does 丫 mean? 丫是什么意思?

Dyck paths with extra diagonals from valleys (Laser construction)

Would it be easier to apply for a UK visa if there is a host family to sponsor for you in going there?

What is an "asse" in Elizabethan English?

Does "shooting for effect" have contradictory meanings in different areas?

What are the discoveries that have been possible with the rejection of positivism?

Drawing spherical mirrors

How were pictures turned from film to a big picture in a picture frame before digital scanning?

Why are vacuum tubes still used in amateur radios?

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?



regex: replace dynamically a searched word



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!A comprehensive regex for phone number validationHow can I merge properties of two JavaScript objects dynamically?Event binding on dynamically created elements?Regular expression to match a line that doesn't contain a wordInteractive search/replace regex in Vim?Converting user input string to regular expressionHow to replace all occurrences of a string in JavaScriptHow to negate specific word in regex?RegEx match open tags except XHTML self-contained tagsPython string.replace regular expression



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I want to replace file:///Downloads/project by a another word like a github link :



const string = 'file:///Downloads/project/users/controllers/users/controller.js';


I tried working with .replace a world by a world but i got in the problem that file:///Downloads/projectis a dynamic value that may change from time to time.



string.replace(/file://Downloads/project/users/controller.js/gi, 'https://gitlab.com')


So i want to search for the word project and replace from it backward by another path or word










share|improve this question

















  • 1





    why do you need regex?

    – alfasin
    Mar 8 at 21:49











  • i'm reading about some way of replacing a substring by regex so i think that's the only ways instead of writing a whole function

    – brxnzaz
    Mar 8 at 21:51











  • string.replace('file:///Downloads/project', 'mynewvalue')

    – Isaac Vidrine
    Mar 8 at 21:51

















0















I want to replace file:///Downloads/project by a another word like a github link :



const string = 'file:///Downloads/project/users/controllers/users/controller.js';


I tried working with .replace a world by a world but i got in the problem that file:///Downloads/projectis a dynamic value that may change from time to time.



string.replace(/file://Downloads/project/users/controller.js/gi, 'https://gitlab.com')


So i want to search for the word project and replace from it backward by another path or word










share|improve this question

















  • 1





    why do you need regex?

    – alfasin
    Mar 8 at 21:49











  • i'm reading about some way of replacing a substring by regex so i think that's the only ways instead of writing a whole function

    – brxnzaz
    Mar 8 at 21:51











  • string.replace('file:///Downloads/project', 'mynewvalue')

    – Isaac Vidrine
    Mar 8 at 21:51













0












0








0








I want to replace file:///Downloads/project by a another word like a github link :



const string = 'file:///Downloads/project/users/controllers/users/controller.js';


I tried working with .replace a world by a world but i got in the problem that file:///Downloads/projectis a dynamic value that may change from time to time.



string.replace(/file://Downloads/project/users/controller.js/gi, 'https://gitlab.com')


So i want to search for the word project and replace from it backward by another path or word










share|improve this question














I want to replace file:///Downloads/project by a another word like a github link :



const string = 'file:///Downloads/project/users/controllers/users/controller.js';


I tried working with .replace a world by a world but i got in the problem that file:///Downloads/projectis a dynamic value that may change from time to time.



string.replace(/file://Downloads/project/users/controller.js/gi, 'https://gitlab.com')


So i want to search for the word project and replace from it backward by another path or word







javascript regex






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 21:47









brxnzazbrxnzaz

1248




1248







  • 1





    why do you need regex?

    – alfasin
    Mar 8 at 21:49











  • i'm reading about some way of replacing a substring by regex so i think that's the only ways instead of writing a whole function

    – brxnzaz
    Mar 8 at 21:51











  • string.replace('file:///Downloads/project', 'mynewvalue')

    – Isaac Vidrine
    Mar 8 at 21:51












  • 1





    why do you need regex?

    – alfasin
    Mar 8 at 21:49











  • i'm reading about some way of replacing a substring by regex so i think that's the only ways instead of writing a whole function

    – brxnzaz
    Mar 8 at 21:51











  • string.replace('file:///Downloads/project', 'mynewvalue')

    – Isaac Vidrine
    Mar 8 at 21:51







1




1





why do you need regex?

– alfasin
Mar 8 at 21:49





why do you need regex?

– alfasin
Mar 8 at 21:49













i'm reading about some way of replacing a substring by regex so i think that's the only ways instead of writing a whole function

– brxnzaz
Mar 8 at 21:51





i'm reading about some way of replacing a substring by regex so i think that's the only ways instead of writing a whole function

– brxnzaz
Mar 8 at 21:51













string.replace('file:///Downloads/project', 'mynewvalue')

– Isaac Vidrine
Mar 8 at 21:51





string.replace('file:///Downloads/project', 'mynewvalue')

– Isaac Vidrine
Mar 8 at 21:51












4 Answers
4






active

oldest

votes


















1














To achieve expected result, use below option of using indexOf and substr and finally replacing with gitlab url



  1. Get index of project

  2. Get string from 0 to index of project

  3. Replace string from step 2 with gitlab using replace option




const string = 'file:///Downloads/project/users/controllers/users/controller.js';
const index = string.indexOf('project')
console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))





codepen - https://codepen.io/nagasai/pen/qvjdEa?editors=1010






share|improve this answer
































    1














    Using regex you can match the first group which includes /project and replace the first parenthesized capture group with your https://gitlab.com. Here p1 denotes first parenthesized capture group and p2 denotes second parenthesized capture group.






    const str = 'file:///Downloads/project/users/controllers/users/controller.js';

    const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
    return 'https://gitlab.com' + p2;
    );

    console.log(res);








    share|improve this answer






























      0














      you don't need a regex for that






      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
      yourValue = "file:///Downloads/project/",
      res = string.replace(yourValue, "https://gitlab.com/")

      console.log(res)








      share|improve this answer

























      • i retreive string dynamically so the value file:///Downloads/project changes

        – brxnzaz
        Mar 8 at 21:52











      • same thing i updated my answer

        – G.aziz
        Mar 8 at 21:53


















      0














      'https://gitlab.com/' + string.substr(string.indexOf('project'))



      First find the position of 'project' in your string



      string.indexOf('project')


      then get a substring from that position to the end of the string (substr goes till the end when no second arg is provided)



      string.substring(indexOfProject)


      then concat it with '+'. Note that the url ends with '/' because your string will begin with 'p'.



      'https://gitlab.com/' + extractedString





      share|improve this answer




















      • 1





        Please explain your answer.

        – Wai Ha Lee
        Mar 9 at 1:05











      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%2f55071462%2fregex-replace-dynamically-a-searched-word%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      To achieve expected result, use below option of using indexOf and substr and finally replacing with gitlab url



      1. Get index of project

      2. Get string from 0 to index of project

      3. Replace string from step 2 with gitlab using replace option




      const string = 'file:///Downloads/project/users/controllers/users/controller.js';
      const index = string.indexOf('project')
      console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))





      codepen - https://codepen.io/nagasai/pen/qvjdEa?editors=1010






      share|improve this answer





























        1














        To achieve expected result, use below option of using indexOf and substr and finally replacing with gitlab url



        1. Get index of project

        2. Get string from 0 to index of project

        3. Replace string from step 2 with gitlab using replace option




        const string = 'file:///Downloads/project/users/controllers/users/controller.js';
        const index = string.indexOf('project')
        console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))





        codepen - https://codepen.io/nagasai/pen/qvjdEa?editors=1010






        share|improve this answer



























          1












          1








          1







          To achieve expected result, use below option of using indexOf and substr and finally replacing with gitlab url



          1. Get index of project

          2. Get string from 0 to index of project

          3. Replace string from step 2 with gitlab using replace option




          const string = 'file:///Downloads/project/users/controllers/users/controller.js';
          const index = string.indexOf('project')
          console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))





          codepen - https://codepen.io/nagasai/pen/qvjdEa?editors=1010






          share|improve this answer















          To achieve expected result, use below option of using indexOf and substr and finally replacing with gitlab url



          1. Get index of project

          2. Get string from 0 to index of project

          3. Replace string from step 2 with gitlab using replace option




          const string = 'file:///Downloads/project/users/controllers/users/controller.js';
          const index = string.indexOf('project')
          console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))





          codepen - https://codepen.io/nagasai/pen/qvjdEa?editors=1010






          const string = 'file:///Downloads/project/users/controllers/users/controller.js';
          const index = string.indexOf('project')
          console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))





          const string = 'file:///Downloads/project/users/controllers/users/controller.js';
          const index = string.indexOf('project')
          console.log(string.replace(string.substr(0, index), 'https://gitlab.com/'))






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 22:01

























          answered Mar 8 at 21:53









          Naga Sai ANaga Sai A

          6,4111927




          6,4111927























              1














              Using regex you can match the first group which includes /project and replace the first parenthesized capture group with your https://gitlab.com. Here p1 denotes first parenthesized capture group and p2 denotes second parenthesized capture group.






              const str = 'file:///Downloads/project/users/controllers/users/controller.js';

              const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
              return 'https://gitlab.com' + p2;
              );

              console.log(res);








              share|improve this answer



























                1














                Using regex you can match the first group which includes /project and replace the first parenthesized capture group with your https://gitlab.com. Here p1 denotes first parenthesized capture group and p2 denotes second parenthesized capture group.






                const str = 'file:///Downloads/project/users/controllers/users/controller.js';

                const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
                return 'https://gitlab.com' + p2;
                );

                console.log(res);








                share|improve this answer

























                  1












                  1








                  1







                  Using regex you can match the first group which includes /project and replace the first parenthesized capture group with your https://gitlab.com. Here p1 denotes first parenthesized capture group and p2 denotes second parenthesized capture group.






                  const str = 'file:///Downloads/project/users/controllers/users/controller.js';

                  const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
                  return 'https://gitlab.com' + p2;
                  );

                  console.log(res);








                  share|improve this answer













                  Using regex you can match the first group which includes /project and replace the first parenthesized capture group with your https://gitlab.com. Here p1 denotes first parenthesized capture group and p2 denotes second parenthesized capture group.






                  const str = 'file:///Downloads/project/users/controllers/users/controller.js';

                  const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
                  return 'https://gitlab.com' + p2;
                  );

                  console.log(res);








                  const str = 'file:///Downloads/project/users/controllers/users/controller.js';

                  const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
                  return 'https://gitlab.com' + p2;
                  );

                  console.log(res);





                  const str = 'file:///Downloads/project/users/controllers/users/controller.js';

                  const res = str.replace(/^(.|/)+w*project(.+)*/gi, function(match, p1, p2)
                  return 'https://gitlab.com' + p2;
                  );

                  console.log(res);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 22:22









                  Farhad YasirFarhad Yasir

                  1,52921430




                  1,52921430





















                      0














                      you don't need a regex for that






                      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
                      yourValue = "file:///Downloads/project/",
                      res = string.replace(yourValue, "https://gitlab.com/")

                      console.log(res)








                      share|improve this answer

























                      • i retreive string dynamically so the value file:///Downloads/project changes

                        – brxnzaz
                        Mar 8 at 21:52











                      • same thing i updated my answer

                        – G.aziz
                        Mar 8 at 21:53















                      0














                      you don't need a regex for that






                      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
                      yourValue = "file:///Downloads/project/",
                      res = string.replace(yourValue, "https://gitlab.com/")

                      console.log(res)








                      share|improve this answer

























                      • i retreive string dynamically so the value file:///Downloads/project changes

                        – brxnzaz
                        Mar 8 at 21:52











                      • same thing i updated my answer

                        – G.aziz
                        Mar 8 at 21:53













                      0












                      0








                      0







                      you don't need a regex for that






                      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
                      yourValue = "file:///Downloads/project/",
                      res = string.replace(yourValue, "https://gitlab.com/")

                      console.log(res)








                      share|improve this answer















                      you don't need a regex for that






                      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
                      yourValue = "file:///Downloads/project/",
                      res = string.replace(yourValue, "https://gitlab.com/")

                      console.log(res)








                      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
                      yourValue = "file:///Downloads/project/",
                      res = string.replace(yourValue, "https://gitlab.com/")

                      console.log(res)





                      const string = 'file:///Downloads/project/users/controllers/users/controller.js',
                      yourValue = "file:///Downloads/project/",
                      res = string.replace(yourValue, "https://gitlab.com/")

                      console.log(res)






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Mar 8 at 21:53

























                      answered Mar 8 at 21:51









                      G.azizG.aziz

                      1,138518




                      1,138518












                      • i retreive string dynamically so the value file:///Downloads/project changes

                        – brxnzaz
                        Mar 8 at 21:52











                      • same thing i updated my answer

                        – G.aziz
                        Mar 8 at 21:53

















                      • i retreive string dynamically so the value file:///Downloads/project changes

                        – brxnzaz
                        Mar 8 at 21:52











                      • same thing i updated my answer

                        – G.aziz
                        Mar 8 at 21:53
















                      i retreive string dynamically so the value file:///Downloads/project changes

                      – brxnzaz
                      Mar 8 at 21:52





                      i retreive string dynamically so the value file:///Downloads/project changes

                      – brxnzaz
                      Mar 8 at 21:52













                      same thing i updated my answer

                      – G.aziz
                      Mar 8 at 21:53





                      same thing i updated my answer

                      – G.aziz
                      Mar 8 at 21:53











                      0














                      'https://gitlab.com/' + string.substr(string.indexOf('project'))



                      First find the position of 'project' in your string



                      string.indexOf('project')


                      then get a substring from that position to the end of the string (substr goes till the end when no second arg is provided)



                      string.substring(indexOfProject)


                      then concat it with '+'. Note that the url ends with '/' because your string will begin with 'p'.



                      'https://gitlab.com/' + extractedString





                      share|improve this answer




















                      • 1





                        Please explain your answer.

                        – Wai Ha Lee
                        Mar 9 at 1:05















                      0














                      'https://gitlab.com/' + string.substr(string.indexOf('project'))



                      First find the position of 'project' in your string



                      string.indexOf('project')


                      then get a substring from that position to the end of the string (substr goes till the end when no second arg is provided)



                      string.substring(indexOfProject)


                      then concat it with '+'. Note that the url ends with '/' because your string will begin with 'p'.



                      'https://gitlab.com/' + extractedString





                      share|improve this answer




















                      • 1





                        Please explain your answer.

                        – Wai Ha Lee
                        Mar 9 at 1:05













                      0












                      0








                      0







                      'https://gitlab.com/' + string.substr(string.indexOf('project'))



                      First find the position of 'project' in your string



                      string.indexOf('project')


                      then get a substring from that position to the end of the string (substr goes till the end when no second arg is provided)



                      string.substring(indexOfProject)


                      then concat it with '+'. Note that the url ends with '/' because your string will begin with 'p'.



                      'https://gitlab.com/' + extractedString





                      share|improve this answer















                      'https://gitlab.com/' + string.substr(string.indexOf('project'))



                      First find the position of 'project' in your string



                      string.indexOf('project')


                      then get a substring from that position to the end of the string (substr goes till the end when no second arg is provided)



                      string.substring(indexOfProject)


                      then concat it with '+'. Note that the url ends with '/' because your string will begin with 'p'.



                      'https://gitlab.com/' + extractedString






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Mar 11 at 16:01

























                      answered Mar 8 at 22:10









                      Jeyko CaicedoJeyko Caicedo

                      313




                      313







                      • 1





                        Please explain your answer.

                        – Wai Ha Lee
                        Mar 9 at 1:05












                      • 1





                        Please explain your answer.

                        – Wai Ha Lee
                        Mar 9 at 1:05







                      1




                      1





                      Please explain your answer.

                      – Wai Ha Lee
                      Mar 9 at 1:05





                      Please explain your answer.

                      – Wai Ha Lee
                      Mar 9 at 1:05

















                      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%2f55071462%2fregex-replace-dynamically-a-searched-word%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

                      Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                      Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                      Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved