首页 > 解决方案 > 正则表达式:动态替换搜索的单词

问题描述

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

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

我尝试使用 .replace a world by a world 工作,但我遇到的问题file:///Downloads/project是一个可能会不时变化的动态值。

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

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

标签: javascriptregex

解决方案


要达到预期的结果,请使用以下使用 indexOf 和 substr 的选项,最后用 gitlab url 替换

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

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


推荐阅读