我想用另一个单词替换file:///Downloads/project
,如github链接:
const string = 'file:///Downloads/project/users/controllers/users/controller.js';
我尝试过.replace一个世界的世界,但我遇到的问题是file:///Downloads/project
is是一个可能不时变化的动态值。
string.replace(/file\:\/\/Downloads\/project\/users\/controller.js/gi, 'https://gitlab.com')
所以我想搜索project
这个词,然后用另一个路径或单词向后替换它
为了达到预期的结果,使用下面的选项使用indexOf和substr,最后用gitlab url替换
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
使用正则表达式,您可以匹配包含/project
的第一个组,并用https://gitlab.com
替换第一个带括号的捕获组。这里p1
表示第一个带括号的捕获组,p2
表示第二个带括号的捕获组。
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 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'))
首先在字符串中找到'project'的位置
string.indexOf('project')
然后从该位置获取一个子串到字符串的末尾(当没有提供第二个arg时,substr一直到结束)
string.substring(indexOfProject)
然后用'+'连接它。请注意,网址以'/'结尾,因为您的字符串将以'p'开头。
'https://gitlab.com/' + extractedString