正则表达式:动态替换搜索到的单词

问题描述 投票:0回答:4

我想用另一个单词替换file:///Downloads/project,如github链接:

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

我尝试过.replace一个世界的世界,但我遇到的问题是file:///Downloads/projectis是一个可能不时变化的动态值。

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

所以我想搜索project这个词,然后用另一个路径或单词向后替换它

javascript regex
4个回答
1
投票

为了达到预期的结果,使用下面的选项使用indexOf和substr,最后用gitlab url替换

  1. 获取项目索引
  2. 获取从0到项目索引的字符串
  3. 使用replace选项用gitlab替换步骤2中的字符串

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


1
投票

使用正则表达式,您可以匹配包含/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);

0
投票

你不需要正则表达式

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

console.log(res)

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

首先在字符串中找到'project'的位置

string.indexOf('project')

然后从该位置获取一个子串到字符串的末尾(当没有提供第二个arg时,substr一直到结束)

string.substring(indexOfProject)

然后用'+'连接它。请注意,网址以'/'结尾,因为您的字符串将以'p'开头。

'https://gitlab.com/' + extractedString
© www.soinside.com 2019 - 2024. All rights reserved.