Regular Expression Domain Name

Quick simple regex question

I have a domain name in the line that I need to delete - there is always http://www. , and the domain always ends with " / "

 g_adv_fullpath_old = g_adv_fullpath_old.replace(/http\:\/\/www\.(.*?)\//ig, ''); 

How to create a regular expression to remove a domain name?

Any help would be appreciated

+4
source share
4 answers

I would just split into "/". For instance:

 >>> "http://www.asdf.com/a/b/c".split("/").slice(3).join("/") 'a/b/c' 
+7
source

Why complications? A simple indexOf will do.
First delete http://www (10 characters), then everything up to the first slash.

 var s = "http://www.google.com/test"; s = s.substr(10); s = s.substr(s.indexOf('/')); alert(s); 

Or split , as David suggests.

Example

+2
source

If you want to remove http://www. and the next slash (plus anything after it) Try:

 g_adv_fullpath_old.replace(/http:\/\/www\.(.*?)\/.*/ig, '$1') 
+2
source

You can also expand the string object to support urlParts

Example

http://jsfiddle.net/stofke/Uwdha/

Javascript

 String.prototype.urlParts = function() { var loc = this; loc = loc.split(/([a-z0-9_\-]{1,5}:\/\/)?(([a-z0-9_\-]{1,}):([a-z0-9_\-]{1,})\@)?((www\.)|([a-z0-9_\-]{1,}\.)+)?([a-z0-9_\-]{3,})((\.[az]{2,4})(:(\d{1,5}))?)(\/([a-z0-9_\-]{1,}\/)+)?([a-z0-9_\-]{1,})?(\.[az]{2,})?(\?)?(((\&)?[a-z0-9_\-]{1,}(\=[a-z0-9_\-]{1,})?)+)?/g); loc.href = this; loc.protocol = loc[1]; loc.user = loc[3]; loc.password = loc[4]; loc.subdomain = loc[5]; loc.domain = loc[8]; loc.domainextension = loc[10]; loc.port = loc[12]; loc.path = loc[13]; loc.file = loc[15]; loc.filetype = loc[16]; loc.query = loc[18]; loc.anchor = loc[22]; //return the final object return loc; }; 

Application:

  var link = "http://myusername: mypassword@test.asdf.com /a/b/c/index.php?test1=5&test2=789#tite"; var path = link.urlParts().path; var path = link.urlParts().user; 
+1
source

Source: https://habr.com/ru/post/1341716/


All Articles