使用这种方法可以安全地require("path").join
连接URL,例如:
require("path").join("http://example.com", "ok");
//returns 'http://example.com/ok'
require("path").join("http://example.com/", "ok");
//returns 'http://example.com/ok'
如果没有,您将建议采用哪种方式而不编写充满ifs的代码?
path.posix.join('/one/two/three', 'four') // '/one/two/three/four
,path.posix.join('/one/two/three/', 'four') // '/one/two/three/four
,path.posix.join('/one/two/three/', '/four') // '/one/two/three/four
path.posix.join('http://localhost:9887/one/two/three/', '/four')
摆脱双斜线之一http://
'http://localhost:9887/one/two/three/'.replace(/^\/+|\/+$/, '') + '/' + '/four'.replace(/^\/+|\/+$/, '')
,你可以做String.prototype.trimSlashes = function() { return this.replace(/^\/+|\/+$/, ''); }
,如果你不想一遍又一遍的键入正则表达式。stackoverflow.com/a/22387870/2537258
['http://localhost:9887/one/two/three/', '/four'].map((part) => part. replace(/^\/+|\/+$/, '')).join('/')