将没有协议的git ssh转换为带协议的git

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

我想转换这个ssh网址

[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)
}

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

javascript regex url url-scheme urlparse
1个回答
2
投票

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

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'))
© www.soinside.com 2019 - 2024. All rights reserved.