我有一个网址,我需要输入一个端口号到网址。 网址不是有效的网址。 这里有几个展示案例:
https://example.com_users/param/param/param - https://example.com_users:8080/param/param/param
http://example.co_setting/param/param/param - http://example.co_settings:1000/param/param/param
http://example.co_setting- http://example.co_settings:1000
const addPort = (url,port) =>{
combined = ???????? // how to combian them
return combined
}
答案 0 :(得分:2)
您可以使用正则表达式:
const addPort = (url, port) =>
url.replace(/^(https?:\/\/)?([^/]*)(\/.*)?$/, '$1' + '$2:' + port + '$3');
console.log(addPort('http://www.example.com/full/url/with/param', '8080'))
答案 1 :(得分:0)
var urlstring = 'https://example.com_users/param/param/param';
var port = ':8080';
var allparts = urlstring.split('//');
var last = allparts[1];
var alllastparts = last.split('/');;
alllastparts[0] = alllastparts[0]+port;
alert(allparts[0]+ '//' + alllastparts.join('/'));
console.log(allparts[0]+ '//' + alllastparts.join('/'));