简体   繁体   中英

regex: replace dynamically a searched word

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/project is 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

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

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); 

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) 

'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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM