Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove hostname and port from url using regular expression

I am trying to remove

http://localhost:7001/

part from

http://localhost:7001/www.facebook.com

to get the output as

www.facebook.com

what is the regular expression that i can use to achieve this exact pattern?

like image 400
mdp Avatar asked Jul 18 '12 21:07

mdp


3 Answers

You don't need any library or REGEX

var url = new URL('http://localhost:7001/www.facebook.com')
console.log(url.pathname)

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

like image 98
Israel Perales Avatar answered Oct 15 '22 01:10

Israel Perales


Based on @atiruz answer, but this is

url = url.replace( /^[a-zA-Z]{3,5}\:\/{2}[a-zA-Z0-9_.:-]+\//, '' );
  • shortest
  • can take https or ftp too
  • can take url with or without explicit port
like image 32
talklesscodemore Avatar answered Oct 15 '22 02:10

talklesscodemore


To javascript you can use this code:

var URL = "http://localhost:7001/www.facebook.com";
var newURL = URL.replace (/^[a-z]{4,5}\:\/{2}[a-z]{1,}\:[0-9]{1,4}.(.*)/, '$1'); // http or https
alert (newURL);

Look at this code in action Here

Regards, Victor

like image 12
atiruz Avatar answered Oct 15 '22 01:10

atiruz