【问题标题】:Convert git ssh without protocol to one with protocol将不带协议的 git ssh 转换为带协议的 git ssh
【发布时间】:2018-07-26 20:17:24
【问题描述】:

我希望转换这个 ssh url

[user@]server:project.git

到这个 ssh 网址

ssh://[user@]server/project.git

我在下面有这个函数,这就是转换字符串所需的全部内容吗?是否有任何故障点或优化?

function getCleanSshUrl (location) {
  let parsedLocation = url.parse(location)
  if (!parsedLocation.protocol) {
    parsedLocation = url.parse(`ssh://${location}`)
    const hasColon = location.match(parsedLocation.hostname + ':')
    if (hasColon) {
      parsedLocation.pathname = parsedLocation.pathname.replace(/^\/:/, '/')
    }
  }
  return url.format(parsedLocation)
}

是否可以在一个正则表达式中完成所有这些操作?

【问题讨论】:

  • 你不是在做一个简单的替换"[user@]server:project.git".replace(/([^:]+):(.*)/, "ssh://$1/$2")吗?
  • 我正在寻找一个正则表达式,它可以为两个字符串 "ssh://[user@]server 产生相同的输出 "ssh://[user@]server/project.git" /project.git”和“[user@]server:project.git”。

标签: javascript regex url url-scheme urlparse


【解决方案1】:

我认为你把事情复杂化了,使用正则表达式来匹配不需要的格式,在其他情况下会返回输入字符串本身:

function getCleanSshUrl (location) {
    return location.replace(/^\s*(\[[^:]+):(.*)/, "ssh://$1/$2");
}

console.log(getCleanSshUrl('[user@]server:project.git'));
console.log(getCleanSshUrl('ssh://[user@]server/project.git'))

【讨论】:

  • 所以在您的第二个示例中,replace 什么都不做,它只是返回传递的字符串,因为没有任何内容与正则表达式匹配,我的意思是 console.log(getCleanSshUrl('ssh://[user@]server/project.git'))
  • 它经历了替换过程,但没有任何反应。其实你也不需要||。查看更新。
猜你喜欢
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2013-04-02
相关资源
最近更新 更多