javascript - 正则表达式:动态替换搜索的单词
问题描述
我想用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
并用另一个路径或单词向后替换
解决方案
要达到预期的结果,请使用以下使用 indexOf 和 substr 的选项,最后用 gitlab url 替换
- 获取项目索引
- 获取从 0 到项目索引的字符串
- 使用替换选项将步骤 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
推荐阅读
- java - 使用jackson&spring mvc将json映射到pojo时,有没有一种方法不需要为布尔字段添加@JsonProperties
- reactjs - 我需要 redux-form 组件来选择几个之一
- react-native - this.props.navigation undefined 不是对象
- sql - 包含 sybase db 中 clob 的条件
- python - Python 时间表:缺少 1 个必需的位置参数?
- sql - 在这种情况下,我收到了缺少关键字错误
- c# - 在 UDF 中映射 CLR 和 SQL SERVER 数据类型
- laravel - 迁移过程中的数据
- python - 我的 NPC 不会追逐我的玩家或对碰撞做出反应
- excel - Excel 公式无法识别非文本值