How do I replace the port number in JavaScript?

You don't need any library or REGEX

var url = new URL('http://localhost:8080');
url.port = '';
console.log(url.toString());

https://developer.mozilla.org/en-US/docs/Web/API/URL

Regrards


This should probably do what you want:

var newUrls = urls.map(function (url) {
    return url.replace(/([a-zA-Z+.\-]+):\/\/([^\/]+):([0-9]+)\//, "$1://$2/");
});

Edit: It seems the schema part of URIs can contain "+", "." and "-" also. Changed the regular expression accordingly.

See: https://en.wikipedia.org/wiki/URI_scheme


One quite nifty way to do this, is to create an a element, and assign the URL you have as href - because the HTMLAnchorElement interface implements URLUtils, and therefor supports accessing the individual parts of the address in the same way the location object does, and you can set them individually as well:

var foo = document.createElement("a");
foo.href = "http://www.example.com:8080/hello/";
foo.port = ""
var newURL = foo.href;
console.log(newURL); // output: http://www.example.com/hello/

http://jsfiddle.net/pdymeb5d/

Tags:

Javascript