gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:12:07 24 4
gpt4 key购买 nike

我想替换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

  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

关于javascript - 正则表达式:动态替换搜索到的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55071462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com