Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace the port number in JavaScript?

Tags:

javascript

I have an array of strings, and I want to create a new array which contains the same strings without port numbers (the port number is a ":" followed by a number). For example if the string is "http://www.example.com:8080/hello/" Then it should be replaced with "http://www.example.com/hello/". How do I do it in JavaScript? I need it to call safari.extension.addContentScriptFromURL because the whitelist can't contain port numbers. If possible, it's better to replace the port number only between the second and third slash and leave the rest of the string unchanged.

like image 563
Uri Avatar asked Sep 11 '14 09:09

Uri


3 Answers

You don't need any library or REGEX

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

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

Regrards

like image 133
Israel Perales Avatar answered Nov 03 '22 15:11

Israel Perales


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/

like image 4
CBroe Avatar answered Nov 03 '22 16:11

CBroe


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

like image 3
Jonathan Steinbeck Avatar answered Nov 03 '22 15:11

Jonathan Steinbeck